DG

dhirendra_gupta

Student at BIT Mesra Aug. 15, 2020, 1:16 p.m. ⋅ 107 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()

 



Go back to feed

HackersFriend Updates





View more


Events


Nov. 28, 2018, 5:30 p.m.

Python from zero to hero

place Delhi

View details


Aug. 13, 2018, 5:30 p.m.

Python from zero to hero

place Bangalore ( HackersFriend office BTM Layout)

View details