File IO
File IO
open
• Open is a function that reads a file and returns a file Object
Open(file,mode,…)
readline([size])
Read until newline or EOF and return a single str. If the stream is
already at EOF, an empty string is returned.
If size is specified, at most size characters will be read.
Return entire file as a string
#get entire file in one shot
f = open("read1.py",’r')
data = f.read() #returns a string of entire file with \n for each line
print("length: ",len(data))
print(data)
Read line by line from file
#get line by line
# open() returns a file object to read2.py for reading text
f = open("read2.py",'r')
counter = 1
for line in f: #loop over the file object and get line by line
print(counter , line)
counter += 1
‘’’note the output when run. Each line has a space?
why? \n in the line and the print function prints then new
line ‘’’
Read line by line from file, another way
‘’’alternative way; note there is no blank lines between each line like in
previous code ‘’’
f = open("read2.py",'r')
#returns a string of entire file split into lines with \n
listOfLines = f.read().split('\n')
print(listOfLines)
counter = 1
‘’’loop over the list of lines and get line by line; Note each line does
not end with \n ‘’’