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
with open('somefile.txt') as f:        # f is the file object
    whole_thing = f.read()

Writing to a file

  • f.write("hi")
    • write the string, no returns unless included with string
  • f.writeline()
    • provide a list of strings to write to the file, no returns unless included in strings of list
with open('somefile', 'w') as filea:   # filea is the file object
    filea.write('hello world')
    filea.write(', time for quiz 5')

somefile content:
hello world, time for quiz 5

file1 = open("Employees.txt", "w")  #file1 is the file object

lst = [] 
for i in range(3): 
    name = input("Enter the name of the employee: ") 
    lst.append(name) 

file1.writelines(lst) 
file1.close() 
print("Data is written into the file.") 

Employees.txt content:

sharonsydneykathryn