Python Write to Text File

Kailash Chandra Behera | Sunday, June 05, 2022

Introduction

Here in this article, we will see examples of how to create a text file in python and load the file into python to write content. Write text to file in append mode in python.

Getting Started

Here in this article, we will see examples of how to create a text file in python and load the file into python to write content. Write text to file in append mode in python.

Write to file in python is as easy as another language. Python also provides various functions to read a file and to write into a file. Here in this article, we will see code examples of how python write to a text file.

Write to File in Python

The following code examples write to file in python, the write() method is used to write the contents to the opened file. The contents can be numbers, text, and binary data. The write functions used to create a text file in python.

 # Program to show in python write to text file  
 _fileobject=open("D:\aricle.txt",'r')#open file w python  
 _fileobject.write("This is new file");#python write to text file  
 print("\nThe contents of aricle.txt are :\n",str)#python printing to file  
 _fileobject.Close() #python close  

open file w python

The above example codes create a text file in python and write data into the file. The article.txt file is created and opened in a write mode and the write function writes the content.

Python Append to File

To add the new data to the end of an already exists file is called appending. To open a file in append mode in python, python open function with ‘a’ mode is used. Append mode in python, the data in the existing file is not overwritten by any new data. It is added to the end of the file.

The following code example opens a file with append mode in python and writes text to the file.

 # Program to show in python write to text file  
 _fileobject=open("D:\aricle.txt",'a')#python append  
 _fileobject.write("This is new file");#python write to text file  
 print("\nThe contents of aricle.txt are :\n",str)#python printing to file  
 _fileobject.Close() #python close  

python append to file

Thanks


No comments: