0% found this document useful (0 votes)
4 views

03.python.06.files

The document provides an overview of file and error handling in programming, detailing how to open, read, write, and close files, along with handling potential access errors. It introduces a try-except pattern for managing exceptions during file operations and emphasizes the importance of user input validation for file names. Additionally, it suggests creating robust functions for file access that repeatedly prompt the user until a valid file is opened.

Uploaded by

dznz1999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

03.python.06.files

The document provides an overview of file and error handling in programming, detailing how to open, read, write, and close files, along with handling potential access errors. It introduces a try-except pattern for managing exceptions during file operations and emphasizes the importance of user input validation for file names. Additionally, it suggests creating robust functions for file access that repeatedly prompt the user until a valid file is opened.

Uploaded by

dznz1999
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

file & error handling

file

• container of data, identified by


• name (+ extension)
• path (relative to the current position, or absolute)

examples:
• “./exefile01.py”
• “/home/bolchini/202425.cs/sourcecode/exefile02.py”

• directory or folder – contains files and


directories
access

open: first operation, before any other action


• mode:
• reading: file must exist and content is not modified
• writing: new file is created and content can be added (if a file
with the same name exists, it is overwritten)
• append: if a file exists, new content is appended at the end of
the previous one

read or write

close: last operation


file opening

• opening statement:

_filehandler_ = open(_filename_, _mode_)

fin = open(“data.txt”, “r”)

fout = open(“results.csv”, “w”)

• fin and fout are the handlers to access the file


once it is open
file opening

with open("data.txt", "r") as fin:


# Further file processing goes here

# no need to close the file


file reading

there is a newline character at the


access to file content end of the line. to remove it

• one line line = fin.readline().strip()

line = fin.readline()
• one line at a time, for all lines in the file
for line in fin:
# use the content of the line

• entire file content acquired in a single operation


text = fin.readlines()
file reading
recap

# read all lines in a file, one line at a time:


for line in fin:
# work on the line
… # line contains "a line in file\n"

# read all lines in a file, one line at a time:


line = fin.readline()
while line: # alternative: while not line == "":
# work on the line
… # line contains "a line in file\n"
# get next line
line = fin.readline()
file reading
recap

# read all lines in a file


# single operation, returns list of strings:
lines = fin.readlines()
… # lines contains ["line1\n", "line2\n", …]

# read all text in a file, single operation


# single string:
alltxt = fin.read()
… # alltxt contains "line1\nline2\n…"
file reading
csv file

• when the content of the file is organized in a


table-like fashion, and entries are separated by a
delimiter, it is possible to optimize the access
• read a line at a time and return a list of the
entries in the line

import csv
file reading
csv file

fin = open(fname, "r")


for line in fin:
lstelem = line.strip().split(",")
print(lstelem)
file reading
csv file

with open(fname, "r") as fin:


reader = csv.reader(fin)
for row in reader:
# row is a list of items
print(row)
file writing

creating file content


strOut = _content_to_be_written_
fout.write(strOut)

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

every other access action raises an exception


access
error handling

• when opening a file it is necessary to verify the


operation successfully completes before
reading/writing
• first handle the most common case when the access
succeeds, then specify behavior when an error
occurred (either require the name of the file again
until correct, or avoid working)

• a specific pattern exists


try except
pattern

• it is a generic exception handling pattern


• it can be adopted every time we expect an erroneous
value (or kind of value) is provider

try:
# perform behavior when everything works fine
except:
# handle error occurrence
try - except
general

• asks the user for an integer and repeats the


acquisition until a proper value is provided, then
it computes and displays True if the value is
prime, False otherwise
try except
file access

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

fname = input(“specify the file name: “)


try:
fout = open(fname”, “w”)
fileok = True
except:
print(“file “ + fname + “ is not accessible .. check the name”)
fileok = False
while not fileok:
try:
fname = input(“specify the file name: “)
fout = open(fname, “w”)
fileok = True
except:
print(“file “ + fname + “ is not accessible .. check AGAIN the name”)
alternative file access

with open(_filename_, _mode_) as _filehandler_:


# work
reading access alternatives

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.

You might also like