Just my personal reference notes for everything related to reading and writing files in Python.
#The open() function returns a stream object, which has methods and attributes for getting information about and manipulating a stream of characters.
f = open("myfile.txt", "r", encoding="utf-8")
print(type(f)) #
print(f.name)
print(f.encoding)
print(f.mode)
#calling the stream object's read() method results in a string.
print(f.read())
#reading the file again does not raise an exception. Python does not consider reading past end-of-file to be an error; it simply returns an empty string.
print(f.read())
#to re-read, the seek() method moves to a specific byte position
f.seek(0)
#The read() method can take an optional parameter, the number of bytes to read.
print(f.read(3))
#subsequent reads will pick up after the previously read bytes
print(f.read(1)) #read the 4th byte
#get the current position
print(f.tell())
f.seek(0)
#f.readline() reads a single line from the file; a newline character (\n) is left at the end of the string, and is only omitted on the last line of the file if the file doesn’t end in a newline. This makes the return value unambiguous; if f.readline() returns an empty string, the end of the file has been reached, while a blank line is represented by '\n', a string containing only a single newline.
print(f.readline())
#read the next line
print(f.readline())
f.seek(0)
#For reading lines from a file, one at a time, you can loop over the file object.
#Besides having explicit methods like read(), the stream object is also an iterator which spits out a single line every time you ask for a value.
for line in f:
#each line is a string
print(line, end="") #pass end argument to avoid default new line
f.seek(0)
print("\n")
#use the readlines() method to get a list of string values from the file, one string for each line of text. Or use list(f)
print(f.readlines())
f.seek(0)
print("\n")
#put into variable and print a subset of the list or a specific line
lines = f.readlines()
print(lines[:3])
f.seek(0)
#read the whole file into a string
contents = f.read()
print("\n")
print(type(contents)) #
#the length of the string
print("\n",len(contents))
print("\n")
print(contents)
#contents is a string so we can print a character by index
print(contents[5])
#we can loop over each character
for char in contents:
print(char)
f.close()
f.closed #true
# The keyword 'with' closes the file once access to it is no longer needed
with open("myfile.txt", "r", encoding="utf-8") as f:
print(f.read())