* 3 min read

Python makes it very quick and easy to read data from files, write data to files, and append data to existing files. These are the three basic file operations for files in Python. The following code will write data to a text file. The file is in the same directory as the runnable Python script. You can change the path of the directory that the file you want to access is located in. Python would create the file if it doesn’t exist.


# =============================================================================
# Open a text file from the same dir as the runnable Python file
# and write to it. Create it if it doesn't yet exist
# =============================================================================

def main():

    f = open('myFile.txt', 'w+') # open file (you can change the file path)

    for i in range(5):
        f.write("Line " + str(i) + "\n") # store some data

    f.close() #close file

if __name__ == "__main__":
    main()

Output in myFile.txt:


Line 0
Line 1
Line 2
Line 3
Line 4

 

Note that we are using ‘w+’ here, which tells Python to open the file in writing mode. The plus sign tells Python to create the file if it doesn’t already exist in that directory. Finally, always close a file after accessing it. The final output would not be seen in the console, since it the data was stored in the file itself, which you need to open to see the data.

The following code is similar to the first. The only difference is that it appends data after the data that is already in the file. Note that running the above code in ‘w+’ (write) mode again would overwrite the existing data in the file, but running it in ‘a+’ (append) mode would append to the already existing data without overwriting it. We also use a plus sign here to tell Python to create the file if it doesn’t exist.


# =============================================================================
# Open a text file from the same dir as the runnable Python file
# and appending to it. Create it if it doesn't yet exist
# =============================================================================

def main():

    f = open('myFile.txt', 'a+') # open file (you can change the file path)

    for i in range(5):
        f.write("Line " + str(i) + "\n") # append some data to already existing data

    f.close() #close file

if __name__ == "__main__":
    main()

Output in myFile.txt:


Line 0
Line 1
Line 2
Line 3
Line 4
Line 0
Line 1
Line 2
Line 3
Line 4


 

To open a file for reading, you can simply open the file in ‘r’ mode for reading from the file rather than writing to it. We can use the common read() or readLines() methods. The first reads the entire contents of the file to memory, while the second reads the file line by line. When working with large datasets, it is always preferred to read and process the file line by line.

# =============================================================================
# Open a text file from the same dir as the runnable Python file
# and read its contents
# =============================================================================

def main():

    f = open('myFile.txt', 'r') # read from a file

    print(f.read()) # read contents in file and print to screen

    f.close() #close file

if __name__ == "__main__":
    main()

Output in console:


Line 0
Line 1
Line 2
Line 3
Line 4
Line 0
Line 1
Line 2
Line 3
Line 4

The following code can also be used to read from the file line by line, rather than the entire contents at once:


f = open('myFile.txt', 'r')
for x in f:
  print(x)

This would print the same output to the console, so it is basically doing the same thing as the code before it, but the only difference is that it is taking one line at a time.

1

Mohammad D.

Mohammad D. works with sentiment anlaysis, NLP and Python. He loves to blog about these and other related topics in his free time.
LinkedIn

Leave a Reply