File IO

How to open a file

# Syntax:
my_file = open('<location_to_file>/<file_name>')

To read that file:

content = myfile.read()

# To print the content
print(content)

Particular read case

content = myfile.read()

data = myfile.read()

print(content)
print(data)
  • The content variable will be printed to screen and does work

  • But the data variable will not print anything to screen

Why does this happen?

  • It has to do of how the .read() method works:

    • It takes the cursor and moves it all the way to the end of the file

    • It does not go back

    • So when printing the second read, the cursor is already at the end of the file

To reset the cursor:

  • Method myfile.seek(0) sets the cursor back to char 0 i.e the beginning of the file

Add each line of file to a list:

Closing the file:

  • If you are reading the file using the above methods, you also want to make sure you are closing the file

  • You cannot have 2 threads doing things with the same file with the above methods

Another way of opening a file is with the with clause:

  • By using the with syntax, you automatically open and close the file

  • This open function also has another argument that it can take, which is the mode=

    • a = append - writes at the end

    • w = write - overwrite the file

    • r = read - only reads from file, cannot write to it (error: not writable)

    • r+ = read and write to the file

    • w+ = used for overwriting a file and reading it after

  • If you change the filename or it does not exist it will create a new file automatically

  • By using r+ it will overwrite the characters starting from the beginning of the file

Last updated