03.python.06.files
03.python.06.files
file
examples:
• “./exefile01.py”
• “/home/bolchini/202425.cs/sourcecode/exefile02.py”
read or write
• opening statement:
line = fin.readline()
• one line at a time, for all lines in the file
for line in fin:
# use the content of the line
import csv
file reading
csv file
file closing
when finished, close file
fin.close()
fout.close()
access
problems when opening
reading:
• file does not exist (maybe wrong name, …)
• user has not permission to access it
writing:
• user has no permission to write in the specific
location of the file system
• there is no space to create a new file
try:
# perform behavior when everything works fine
except:
# handle error occurrence
try - except
general
try:
# try opening file
fileok = True
except:
# show some error message to help the user
fileok = False
while not fileok:
try:
# try opening file
fileok = True
except:
# show some error message to help the user
try except
example
we ask the user the name of the file the name of the file is given
fname = input()
try: CTABLE = "files.macro.csv"
fin = open(fname,"r") SEP = ","
fok = True
cdict = {}
except:
try:
print("problems with " + fname)
fok = False with open(CTABLE, "r") as fin:
while fok == False: for line in fin:
fname = input("retry: ") info = line.strip().split(SEP)
try:
cdict[info[0]] = info[1]
fin = open(fname,"r")
print(cdict)
fok = True
except: except:
print("still problems" + fname) print("file " + CTABLE + " not found")
# file is now open
txtlst = fin.readlines()
fin.close()
"robust" file opening function
write a function that receives as a parameter the mode to access a file (e.g., for reading,
writing, …) and asks the user the name of the file to be opened and returns the handle to
the open file. If there are problems in accessing the file, the request is repeated
"robust" file opening function (with name)
write a function that receives as parameters the name of the file to be opened and the mode
to access it (e.g., for reading, writing, …) and returns the handle to the open file. If
there are problems in accessing the file, the name is asked the user until the file opens.
The function also returns the name of the opened file.