The Right Way to Read and Write Files

148次阅读
没有评论

A fundamental need in nearly any programming language is the ability to interact with files. Whether you’re reading configuration settings, processing a data set, or saving the results of your work, handling files correctly is a crucial skill. Python makes this process remarkably simple and safe, provided you use its modern context manager syntax.

Let’s explore how to read from and write to a simple text file.

The Old Method: Manual open() and close()

In some older code or tutorials, you might see files being handled by manually opening them and then remembering to close them when you’re done.

Python

# The manual, less-safe way
f = open('my_file.txt', 'w') # 'w' stands for write mode
f.write('Hello, world!\n')
f.write('This is the old way to write to a file.\n')
f.close() # You must remember to close the file

The major problem with this approach is that it’s fragile. If an error occurs after open() but before f.close() is called, the program might crash, and the file could be left open. This can lead to resource leaks or corrupted data, especially in larger applications. To make this safe, you would need to wrap it in a try...finally block, which adds more boilerplate code.

The Pythonic Way: The with Statement

The best practice for handling resources like files in Python is the with statement. It acts as a “context manager,” ensuring that setup and teardown operations are always performed. For files, this means the file is guaranteed to be closed automatically when you are done with it, even if errors occur within the block.

Here’s how you write to a file using this modern, safe approach:

Python

# The modern, safe way to write a file
lines_to_write = [
    'Hello from the with statement!',
    '\nThis is much safer.',
    '\nThe file will close itself automatically.'
]

with open('my_safe_file.txt', 'w') as f:
    f.writelines(lines_to_write)
    # No need to call f.close(). The 'with' block handles it.

print("File has been written.")

How to Read a File

Reading a file follows the same safe pattern. You open the file in read mode ('r') and can then treat the file object f as an iterable, allowing you to loop through its lines directly.

Python

# The modern, safe way to read a file
print("\nReading the file's contents:")
try:
    with open('my_safe_file.txt', 'r') as f:
        for line in f:
            # The print function adds a newline, so we use .strip() to remove the extra one from the file
            print(line.strip()) 
except FileNotFoundError:
    print("The file was not found!")

This syntax is not only safer but also more readable. It clearly defines the scope where the file is being used. Once the code execution leaves the indented with block, the file is closed.

Bonus Tip: Appending to a File

If you want to add content to the end of an existing file without deleting its contents, you can use the append mode, 'a'.

Python

with open('my_safe_file.txt', 'a') as f:
    f.write('\nAdding a new line at the end.')

Always use the with statement for file I/O. It’s one of the most useful features in Python for writing clean, robust, and error-resistant code. See you tomorrow!

正文完
 0
评论(没有评论)
验证码