Read and write text files in Python, choose the right file mode, and use the with statement to close files safely.
Author
Gujuri Alekha
Published
Oct 20, 2024
5.1 Reading and Writing Text Files
Reading Files: You can read the contents of a text file in Python using the open() function.
Writing Files: To write data to a text file, you can open the file in write mode (‘w’) or append mode (‘a’).
Show code
## we open the file named 'example.txt' in read mode ('r') and use the read() method to read its contents into the content## variable. The with statement is used to ensure that the file is properly closed when we're done with it.open('example.txt', 'r') asfile: content =file.read()print(content)## we open 'example.txt' in write mode ('w') and use the write() method to write the text 'Hello, World!' to the file.## The '\n' character represents a newline, so the text will be on a new line.withopen('example.txt', 'w') asfile:file.write('Hello, World!\n')
5.2 File Modes
File modes specify how a file should be opened, whether for reading, writing, or appending. Common file modes in Python include:
‘r’: Read mode - Opens the file for reading (default mode).
‘w’: Write mode - Opens the file for writing. If the file already exists, it will be truncated (emptied). If it doesn’t exist, a new file will be created.
‘a’: Append mode - Opens the file for writing, but does not truncate it. If the file doesn’t exist, a new file will be created.
‘b’: Binary mode - Used in combination with other modes to indicate that the file should be treated as a binary file (e.g., ‘rb’, ‘wb’).
5.3 Using Context Managers (with Statement)
The with statement in Python is used for context management, particularly for resources that need to be acquired and released properly, such as files. When you open a file using with, Python ensures that the file is properly closed when you’re done, even if an exception occurs during execution. This helps in avoiding resource leaks.
When the code inside the with block finishes executing (in this case, reading the file), Python automatically closes the file, ensuring that you don’t have to explicitly call file.close().
Show code
withopen('example.txt', 'r') asfile:
Get new notebooks as they're published
New parts are added to each track in order. Follow along: