Hoorcollege 11:
Openen en bewerken van tekst bestanden:
fh1 = open(‘myfile.txt’, “r”) # open for reading
fh1 = open(‘myfile.txt’, “w”) # open for writing, remove existing content
fh1 = open(‘myfile.txt’, “a”) # open for writing, keep existing content
fh1.readline() # read single line
fh1.readlines() # read a list of lines
fh1.read(7) # read the next 7 characters
fh1.strip() # strips the file of empty lines
fh1.write(“Hallo World\n”) # write text to file, not explicit newline at the
end
fh1.close() # close a file after use
with open(‘file.txt’, ‘r’) # no closing using with()
Openen en lezen van csv bestanden:
import csv
fh1 = open(‘csv_file.csv’) # open file for reading
ch1= csv.reader(fh1) # create a csv variable from the file handle
regel = next(ch1) # eerste regel
regel[i] # i’e element van de eerste regel
Bewerken van csv bestanden:
ch1 = csv.writer(fh1) # create write file
ch1.writerow(content) # write row and fill with content
fh1.close() # close starting file
Try en except:
try block: tests a block of code for errors
except block: handles the error
else: execute the code when there is no error
finally: executes code regardless of the result