9.1 File Input and Output Operations
Open this guide for a closer review of the topic.
File I/O and exception handling are crucial skills for programmers. These techniques allow you to read from and write to files, store data persistently, and handle errors gracefully in your code. Learning file operations and exception handling empowers you to create robust programs that interact with external data sources. These skills are essential for developing applications that can process, store, and retrieve information effectively.
Start with the review notes if you need the full unit, or jump to the section you are reviewing today.
File I/O and exception handling are crucial skills for programmers. These techniques allow you to read from and write to files, store data persistently, and handle errors gracefully in your code. Learning file operations and exception handling empowers you to create robust programs that interact with external data sources. These skills are essential for developing applications that can process, store, and retrieve information effectively.
Open this guide for a closer review of the topic.
Open this guide for a closer review of the topic.
Open this guide for a closer review of the topic.
Open this guide for a closer review of the topic.
.txt for text files, .jpg for images)
read(), readline(), or readlines()
read() reads the entire contents of the file as a single stringreadline() reads a single line from the filereadlines() reads all lines and returns them as a list of stringsw) overwrites the existing file content if the file already existsa) adds new data to the end of the file, preserving the existing contentwrite() and writelines()
write() writes a single string to the filewritelines() writes a list of strings to the filetry, except, and optionally finally blocks
try block contains the code that may raise an exceptionexcept block specifies the code to handle specific exceptionsfinally block contains cleanup code that always executes, regardless of exceptionsexcept blocks can be used to handle different types of exceptions separatelyraise statement allows custom error handlingFileNotFoundError: Raised when trying to open a file that does not existPermissionError: Raised when the program lacks sufficient permissions to access or modify a fileIOError: Raised when an input/output operation fails, such as reading from or writing to a fileValueError: Raised when attempting to read or write data in an invalid formatUnicodeDecodeError: Raised when encountering an error while decoding Unicode characters from a fileOSError: Raised when an operating system-related error occurs during file operationswith statement for automatic file closing and exception handlingcsv or json for handling structured file formats efficiently</>Pythonwith open('example.txt', 'r') as file: line_count = 0 for line in file: line_count += 1 print(f'The file has {line_count} lines.')
</>Pythondata = ['New line 1', 'New line 2', 'New line 3'] with open('example.txt', 'a') as file: file.writelines('\n'.join(data))
</>Pythontry: with open('nonexistent.txt', 'r') as file: content = file.read() except FileNotFoundError: print('The specified file does not exist.') except IOError: print('An error occurred while reading the file.')
</>Pythonwith open('source.txt', 'r') as source_file, open('destination.txt', 'w') as dest_file: content = source_file.read() dest_file.write(content)
Open the individual guides for Unit 9 when you want a closer review of one topic.
browse guides