Reading a file

  • allcontent = f.read()
    • returns the entire file content as a string
  • f.readlines()
    • returns a list of strings
    • each line in the file is a string, \n is part of the string
  • f.readline()
    • file marker
    • returns one line as a sting including the \ns

example.txt

hello
this is an example of a file for CS149
1
2

myfile = open('example.txt')
whole = myfile.readlines()

print(f'Here is the list: \n{whole}\n')
for item in whole:
    print(item[:-1])  # don't print \n
    
print(f'The type of whole is {type(whole)} and the length of whole is {len(whole)}')
print(f'An entry in the list is of {type(whole[0])} and the 2nd entry is {whole[1]}') 

print(f'Converting to int and summing: {int(whole[2]) + int(whole[3])}')
print(f'Capitalizing a string of the list: {whole[0].upper()}')

funny_str = whole[1][0:3] + whole[-1]
print(funny_str)
Here is the list: 
['hello\n', 'this is an example of a file for CS149\n', '1\n', '2\n']

hello
this is an example of a file for CS149
1
2
The type of whole is <class 'list'> and the length of whole is 4
An entry in the list is of <class 'str'> and the 2nd entry is this is an example of a file for CS149

Converting to int and summing: 3
Capitalizing a string of the list: HELLO

thi2

Another way to read

with open('example.txt') as ex:
    str = ""
    for line in ex:
        print(type(line))    # string
        if len(line) > 4:
            str += line[2:4].upper()

print(str)