Mastering Python: a Comprehensive Guide by Américo Moreira
Author:Américo Moreira
Language: eng
Format: epub
Publisher: Ocirema
Published: 2023-09-29T00:00:00+00:00
Chapter 7 - File Handling and Input/Output
7.1 Reading and Writing Files
In Python, file handling is an essential skill that allows you to work with different types of files, such as text files, CSV files, JSON files, and more. In this section, we will explore how to read and write files using Python.
Opening and Closing Files
Before we can read or write to a file, we need to open it. Python provides a built-in function called open() that allows us to open a file in different modes, such as read mode ('r'), write mode ('w'), append mode ('a'), and more. Hereâs the basic syntax for opening a file:
file = open('filename', 'mode')
In the above syntax, 'filename' represents the name of the file you want to open, and 'mode' represents the mode in which you want to open the file.
Once we are done working with a file, it is important to close it to free up system resources. We can use the close() method to close the file. Hereâs an example:
file = open('filename', 'mode')
# Perform file operations
file.close()
Reading Files
To read the contents of a file, we can use the read() method. This method reads the entire contents of the file as a string. Hereâs an example:
file = open('filename', 'r')
content = file.read()
print(content)
file.close()
In the above example, we open the file in read mode ('r'), read its contents using the read() method, and then print the content. Finally, we close the file using the close() method.
If you want to read only a certain number of characters from a file, you can pass the number of characters as an argument to the read() method. For example, to read the first 100 characters of a file, you can use the following code:
file = open('filename', 'r')
content = file.read(100)
print(content)
file.close()
Writing Files
To write to a file, we need to open it in write mode ('w'). If the file does not exist, Python will create it. If the file already exists, opening it in write mode will overwrite its contents. Hereâs an example:
file = open('filename', 'w')
file.write('Hello, World!')
file.close()
In the above example, we open the file in write mode ('w'), write the string 'Hello, World!' to the file using the write() method, and then close the file.
If you want to append content to an existing file instead of overwriting it, you can open the file in append mode ('a'). Hereâs an example:
file = open('filename', 'a')
file.write('This is additional content.')
file.close()
In the above example, we open the file in append mode ('a'), write the string 'This is additional content.' to the file, and then close the file.
Error Handling
When working with files, it is important to handle potential errors that may occur. One common error is when the file you are trying to open does not exist. To handle such errors, you can use a try-except block. Hereâs an example:
try:
file = open('filename', 'r')
content = file.read()
print(content)
file.close()
except FileNotFoundError:
print('File not found.')
In the above example, we try to open the file and read its contents. If the file does not exist, a FileNotFoundError will be raised, and the code inside the except block will be executed.
Download
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.
Hello! Python by Anthony Briggs(9867)
OCA Java SE 8 Programmer I Certification Guide by Mala Gupta(9757)
The Mikado Method by Ola Ellnestam Daniel Brolund(9747)
Algorithms of the Intelligent Web by Haralambos Marmanis;Dmitry Babenko(8258)
Sass and Compass in Action by Wynn Netherland Nathan Weizenbaum Chris Eppstein Brandon Mathis(7745)
Test-Driven iOS Development with Swift 4 by Dominik Hauser(7741)
Grails in Action by Glen Smith Peter Ledbrook(7667)
The Well-Grounded Java Developer by Benjamin J. Evans Martijn Verburg(7517)
Windows APT Warfare by Sheng-Hao Ma(6502)
Secrets of the JavaScript Ninja by John Resig Bear Bibeault(6378)
Layered Design for Ruby on Rails Applications by Vladimir Dementyev(6248)
Blueprints Visual Scripting for Unreal Engine 5 - Third Edition by Marcos Romero & Brenden Sewell(6117)
Kotlin in Action by Dmitry Jemerov(5019)
Hands-On Full-Stack Web Development with GraphQL and React by Sebastian Grebe(4297)
Functional Programming in JavaScript by Mantyla Dan(4018)
Solidity Programming Essentials by Ritesh Modi(3839)
WordPress Plugin Development Cookbook by Yannick Lefebvre(3614)
Unity 3D Game Development by Anthony Davis & Travis Baptiste & Russell Craig & Ryan Stunkel(3565)
The Ultimate iOS Interview Playbook by Avi Tsadok(3532)
