Python reading and writing files

Python has several functions for creating, reading, updating, and deleting files.

file handling

  • open built in function is used to work with files for reading/writing.
  • four different modes to open a file
    • "r" - Read
      • Opens a file for reading, error if the file does not exist
    • "a" - Append
      • Opens a file for appending, creates the file if it does not exist
    • "w" - Write
      • Opens a file for writing, creates the file if it does not exist
    • "x" - Create
      • Creates the specified file, returns an error if the file exists
    • "t" - Text
      • Default value. Text mode
    • "b" - Binary
      • Binary mode (e.g. images)

Note: we can use multiple modes at the same time like rb, rw, etc.

read contents of an existing file

  • let's say we have file named names.csv

names.csv

John
Ram
Kareem
Buddha
  • let's write the code to read the file.
f = open("names.csv", "r")
print(f.read())
f.close()
  • the above code also equivalent to below code
with open("names.csv", "r"):
    print(f.read())
    f.close()
  • whenever you open a file it's good practice to close it. because, when we open a file it loads into the memory if we call close() method then it removes the reference to that memory.

  • above program gives the following output.

John
Ram
Kareem
Buddha

write contents to an existing file

  • let's write some names to file named friends.csv
friends = ["John", "Dwyne", "Kalki"]
with open('/tmp/friends.csv', 'w') as f:
    for name in friends:
        f.write(name+"\n")
  • above program overrides the existing contents if file exists and writes the friend names to the file.

append contents to an existing file

  • let's append names to file named friends.csv
friends = ["John", "Dwyne", "Kalki"]
with open('/tmp/friends.csv', 'a') as f:
    for name in friends:
        f.write(name+"\n")
  • above program will add friends names to the file friends.csv
  • It won't override existing contents of the file.

reading & writing file with a encoding

  • encoding can be "utf-8", "latin-1", etc.
  • default it uses "utf-8" encoding
  • let's look at the code sample
with open('/tmp/data.txt', "rw", encoding="latin-1") as f:
    # do something
    pass

Note: you can only do operations based on the file open mode.

reading binary files

  • we can read binary files like images and videos, etc.
  • let's write code to read an image
img_file_path = '/tmp/abcd.png'
with open('/tmp/data.txt', "rb") as f:
    binary_data = f.read()
    # do something

TextIOWrapper & BufferedReader

  • If we open a file with mode r, w etc. other than binary b then the contents are loaded into class TextIOWrapper
  • If we open a file with mode b then the contents are loaded into class BufferedReader
  • Base the loaded class we can use the available methods & attributes related to the class.

References: