Tutorials  Articles  Notifications  Login  Signup


DG

Dhirendra Gupta

Student at BIT Mesra Aug. 15, 2020, 1:16 p.m. ⋅ 655 views

Python Write File


We can use open() function to write into a file or create a new file.

open() function accepts 2 parameters:

  1. FileName
  2. Mode

We have following modes available:

  • "x" - Create - will create a file, returns an error if the file exist
  • "a" - Append - will create a file if the specified file does not exist
  • "w" - Write - will create a file if the specified file does not exist

Take a look at implementations.

# Create a new File, return error if file exists

f = open("sampleFile.txt", "x")
#Create a new file if it doesn't exist, overwrite if exists

f = open("sampleFile.txt", "w")
# Append in existing file, don't overwrite

f = open("sampleFile.txt", "a")

To write anything into file we can use write() method, after writing into file we must close the file.

f = open("sampleFile.txt", "w")
f.write("Overwrite existing if there was any. Or create a new file.")
f.close()

Add more content into file by opening it into append mode. 

f = open("sampleFile.txt", "a")
f.write("Add more new content in our existing file.")
f.close()

 



HackerFriend Logo

Join the community of 1 Lakh+ Developers

Create a free account and get access to tutorials, jobs, hackathons, developer events and neatly written articles.


Create a free account