Python: Files Handling

None of the data has been preserved in all the coding so far. We created variables, lists, dictionaries, and class instances that contained information, but it disappeared when the computer was turned off.
You know how to save a word-processing document or spreadsheet, but how do you save data processed by Python?

Reading Writing in an external file from Python Code

We can write in a text file by using a Python function:

open("file_name.txt","mode")

There are three modes:

  • Read
  • Write
  • Append

Writing to a Text File

file = open("myFile.txt", "w")
file.write("This is my file")

Note: If a file does not exist, “w” mode creates and writes in it.

Reading from a Text File

file = open("myFile.txt", "r")
print(file.read())

Note: If the file does not exist, “r” mode will throw file not found error

Writing a file in append mode

file = open("myFile.txt", "a")
file.write("This text is written in append mode")

Note: in “w” mode if we write in the same file all previous work will be overwritten. But append mode allows you to write further.