Write to File in Python

Write to File in Python

Save the output of your program so that it doesn’t get lost when you close your program, we save it in a file.

The Simplest way to save any type of out is to write and save it as a text file.

With python you can save any “string” to a .txt file and read it later.

How to write to .txt file in python?

To write data in a txt file python uses the ‘write’ function. But before we write the file we need to open the file by using the ‘open function’. Remeber to close the file by using ‘close()’ function to safely save the file.

Demo code to open and write data in a file [Python.]

data='Save this in a txt file\n'
f = open("newfile.txt", "w")
f.write(data)
f.close()

The above program saves the string variable ‘data’ in a file name “newfile.txt”.

But, There is a problem, it will clear all file first and then write the data in the file when ever the program is run.

So, to handle this problem the open method has two modes

  • ‘w’ for write mode- which first clears the file and then write . f = open(“newfile.txt”, “w”).
  • ‘a’ for append -mode which leaves the data in file as it is and adds/ appends the new data at the end of the existing data. f = open(“newfile.txt”, “a”)

Demo Code to append file in [python]

data='Save this in a txt file\n'
f = open("newfile.txt", "w")
f.write(data)
f.close()

The above program appends the new data in the same file without clearing the previosly written data.

Bonus:

Both ‘w’ and ‘a’ mode of the open function will create a file if the file does not exist.

Additionally, open function in ‘x’ mode which will create a new file if does not exist and throws an error if the file name exist

data='Save this in a txt file\n'
f = open("newfile.txt", "x")
f.write(data)
f.close()

The above program creates a “newfile.txt” and writes the data in it, but if you run the program again it will throw an error because the file “newfile.txt” has been already created.


Thank you for reading, Happy Learning, drop your suggestion in the comments.

Feel free to follow us on Youtube, Linked In , Instagram

Loading comments...
Mastodon