Python Write to Text File

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

Kailash Chandra Behera

An IT Professional with 12 years experience in development life cycle in windows, service and Web based application using Microsoft.Net technologies. Proven record of developing all phases of projects in Microsoft.Net technology from initiation to closure aligning with the company's Business objectives to drive process improvements, competitive advantage and bottom-line gains. -> Good exposure of independently working and developing multiple projects ->Committed to efficient and effective development of projects in a fast-paced and deadline driver environment. Skill :- Develop and design projects in various technologies of Microsoft Technology. Total IT Experience- 13+

Previous Post Next Post

نموذج الاتصال