Reading an entire file

with open('file') as file_object:
    contents = file_object.read()
    print(contents)
  • open opens the file and returns a file object that is saved in file_object variable.
  • with closes the file when it is no longer needed. So, we don't need to warry about when to close the file.
  • read reads the contents of the file.
  • print prints the contents of the file.

There is one difference between the output and the content of the file that is an extra blank line at the end. when read reaches the end of file it reads an empty string which appears as an extra blank line. To remove it use rstip as follows

with open('file') as file_object:
    contents = file_object.read()
    print(contents.rstip())

Reading line by line

You can use a for loop on the file object to examine each line from a file one at a time.

with open('file') as file_object:
    for line in file_object:
        print(line)

The print statement adds a newline and each line from a file ends with a newline. To eliminate the extra newlines you can use either print(line.rstrip()) or print(line, end="")

The file_object scope The file_object returned by open is only available inside the with block. To access a file's contents outside the with block you need to store it in a variable (i.e. list). For example

with open('file') as file_object:
    lines =  file_object.readlines()

for l in lines:
    print(l.rstrip())

When Python reads from a text file, it interprets all text in the file as a string. If you read in a number and want to work with that value in a numerical context, you'll have to convert it to either an integer using the int() function or a float using the float() funciton.

Write to a file

To write to a file you need to open it in write mode by adding the second argument w to the open() function. Then you can write to the file by calling the write() method on the file object as follows

with open('file', 'w') as file_object:
    file_object.write("I love learning \nPython in paticular is my favorite")

In Python you can open a file in:

  • read mode open('file_name', 'r') or open('file_name')
  • write mode like this open('file_name', 'w')
  • read and write mode like this open('file_name', 'r+')
  • append mode like this open('file_name', 'a')

Opening a file in write mode will create it if it is not exist or erase it otherwise.
To continue writing on the next line you need to add \n (newline) to the string