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:

content = myfile.read()
print(content)

myfile.seek(0) # Resets the cursor back to position 0

data = myfile.read()
print(data)
  • 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:

# Saves each line as a separate element in a list
content_list = myfile.readlines()

print(content_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

# Closing the file
myfile.close()

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

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

# Syntax:
with open(<file_location>/<file_name>) as <variable_name_you_want_to_use>:
	content = variable_name_you_want_to_use.read()

print(content)
  • 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

with open(file_name, mode='a') as myfile:
	# Will be appended at the end of the file
	myfile.write("\nWrite a sentence") # Will also append on new line
  • If you change the filename or it does not exist it will create a new file automatically

with open(new_file_name, mode='a') as myfile:
	myfile.write("\nWrite a sentence")
  • By using r+ it will overwrite the characters starting from the beginning of the file

with open(new_file_name, mode='r+') as myfile:
	myfile.write("\nWrite a sentence")

Last updated