Resources | Subject Notes | Computer Science
This section explores how to read data from and write data to files in Python. It also covers the crucial aspect of exception handling to gracefully manage errors that may occur during file operations.
Before any file processing can occur, a file must be opened. Python provides the open()
function for this purpose. The open()
function takes two main arguments: the filename and the mode.
'r'
: Read mode (default). Opens the file for reading. An error occurs if the file does not exist.'w'
: Write mode. Opens the file for writing. If the file exists, its contents are overwritten. If the file does not exist, a new file is created.'a'
: Append mode. Opens the file for writing. New data is added to the end of the file. If the file does not exist, a new file is created.'x'
: Exclusive creation mode. Opens a file for exclusive creation. If the file already exists, the operation fails.'b'
: Binary mode. Used in conjunction with other modes (e.g., 'rb', 'wb') to open the file in binary mode.'t'
: Text mode (default). Used in conjunction with other modes (e.g., 'rt', 'wt') to open the file in text mode.'+'
: Update mode. Used in conjunction with other modes (e.g., 'r+', 'w+', 'a+') to allow both reading and writing.It is essential to close the file after processing using the close()
method. Alternatively, the with
statement provides a more convenient way to ensure that the file is automatically closed, even if exceptions occur.
Example:
with open('my_file.txt', 'r') as f:
data = f.read()
print(data)
# The file is automatically closed here
Several methods are available for reading data from files:
read()
: Reads the entire contents of the file into a single string.readline()
: Reads a single line from the file.readlines()
: Reads all lines from the file and returns them as a list of strings.Example:
with open('my_file.txt', 'r') as f:
for line in f:
print(line.strip())
Data can be written to files using the write()
method. The write()
method takes a string as an argument and writes it to the file.
Example:
with open('output.txt', 'w') as f:
f.write('This is the first line.\n')
f.write('This is the second line.\n')
To append data to an existing file, use the 'a' mode.
with open('output.txt', 'a') as f:
f.write('This line is appended.\n')
Exception handling is crucial for robust file processing. Errors can occur during file operations, such as the file not existing, insufficient permissions, or disk errors. The try...except
block allows you to catch and handle these exceptions.
Common exceptions encountered during file operations include:
FileNotFoundError
: Raised when the specified file does not exist.PermissionError
: Raised when the program does not have the necessary permissions to access the file.IOError
: A general exception for input/output errors.Example:
try:
with open('nonexistent_file.txt', 'r') as f:
data = f.read()
print(data)
except FileNotFoundError:
print('Error: The file does not exist.')
except PermissionError:
print('Error: You do not have permission to access this file.')
except IOError:
print('Error: An input/output error occurred.')
except Exception as e:
print(f'An unexpected error occurred: {e}')
This example demonstrates reading a file and counting the number of words in it.
def count_words(filename):
try:
with open(filename, 'r') as f:
content = f.read()
words = content.split()
return len(words)
except FileNotFoundError:
return 'Error: File not found.'
except Exception as e:
return f'An error occurred: {e}'
filename = 'example.txt'
word_count = count_words(filename)
print(f'The file "{filename}" contains {word_count} words.')
Mode | Description | Behavior |
---|---|---|
'r' |
Read | Opens the file for reading. Raises an error if the file does not exist. |
'w' |
Write | Opens the file for writing. Overwrites existing content or creates a new file. |
'a' |
Append | Opens the file for appending. Adds new content to the end of the file or creates a new file. |
'x' |
Exclusive Creation | Creates a new file. Raises an error if the file already exists. |
'b' |
Binary | Opens the file in binary mode. |
't' |
Text | Opens the file in text mode. |
'+' |
Update | Allows both reading and writing. |
This section provides a foundation for working with files in Python. Understanding file modes and exception handling is essential for writing robust and reliable programs.