杰瑞科技汇

Python如何写入文本文件?

Of course! Writing text to a file in Python is a fundamental task. I'll guide you through the most common methods, from the simplest to more advanced and robust techniques.

Python如何写入文本文件?-图1
(图片来源网络,侵删)

The Short and Sweet Answer (The Modern Way)

For most cases, especially in Python 3, this is the recommended approach. It's clean, safe, and automatically closes the file for you.

text_to_write = "Hello, Python!\nThis is a second line of text."
# 'w' mode means "write". It will create the file if it doesn't exist,
# or overwrite it if it does.
with open('my_file.txt', 'w') as f:
    f.write(text_to_write)
print("File written successfully!")

Detailed Breakdown

Let's break down what's happening in that simple example.

The open() function

To work with a file, you first need to open it. The open() function does this.

file_object = open(filename, mode)
  • filename: A string containing the path to your file. If the file is in the same directory as your script, you can just use the filename (e.g., 'my_file.txt'). For a different directory, use a full path (e.g., 'C:/Users/YourUser/Documents/my_file.txt').
  • mode: This is a crucial argument that tells Python what you intend to do with the file. The most common modes are:
    • 'r': Read (default). Opens a file for reading. Fails if the file doesn't exist.
    • 'w': Write. Opens a file for writing. Creates the file if it doesn't exist. If it does exist, it will be completely overwritten.
    • 'a': Append. Opens a file for appending. Creates the file if it doesn't exist. If it does exist, new data is added to the end of the file without deleting the old content.
    • 'r+': Read and Write. Opens a file for both reading and writing. The file pointer is at the beginning.

The with Statement (Context Manager)

This is the best practice for handling files in Python.

Python如何写入文本文件?-图2
(图片来源网络,侵删)
with open('my_file.txt', 'w') as f:
    # ... do something with the file ...
  • Why use it? The with statement automatically handles closing the file for you, even if errors occur inside the block. This is called a context manager.

  • Why is this important? If you don't close a file, it can lead to resource leaks. Your program might keep the file locked, preventing other programs from accessing it, or it might not save all the data properly.

  • as f: This assigns the opened file object to a variable named f (a common convention, you could use file, myfile, etc.). You'll use this variable to perform operations on the file.

The write() method

Once you have a file object, you can use methods to interact with it.

  • file_object.write(string): Writes the string to the file. It returns the number of characters written.
  • file_object.writelines(list_of_strings): Writes a list of strings to the file. Note: It does not add newlines (\n) between the strings for you. You must add them to the strings in your list if you want them.

Common Scenarios and Examples

Here are more examples covering different situations.

Scenario 1: Appending to a File (instead of overwriting)

Use mode 'a' to add new content to the end of an existing file.

# Let's assume 'my_file.txt' already exists and has "Hello, Python!" in it.
new_text = "\nThis line was appended."
with open('my_file.txt', 'a') as f:
    f.write(new_text)
# Now 'my_file.txt' contains:
# Hello, Python!
# This line was appended.

Scenario 2: Writing Multiple Lines at Once

Using writelines() is efficient, but remember to handle the newlines yourself.

lines_to_write = [
    "This is the first line.\n",
    "This is the second line.\n",
    "This is the final line.\n"
]
with open('multiline_file.txt', 'w') as f:
    f.writelines(lines_to_write)
# The file will look like:
# This is the first line.
# This is the second line.
# This is the final line.

Scenario 3: Handling Different File Paths

It's good practice to use os.path to build file paths, as it works correctly on Windows, macOS, and Linux.

import os
# Get the current directory where the script is running
current_dir = os.getcwd()
# Define the filename and the full path
filename = 'output.txt'
file_path = os.path.join(current_dir, 'data', filename) # Creates a path like 'data/output.txt'
# Make sure the 'data' directory exists
os.makedirs(os.path.dirname(file_path), exist_ok=True)
text = "Writing to a specific directory."
with open(file_path, 'w') as f:
    f.write(text)
print(f"File written to: {file_path}")

Important Considerations

Encoding

If you are writing text that contains non-English characters (like accents, emojis, or Chinese characters), you must specify an encoding. The default encoding can vary depending on the system.

The best practice is to always use utf-8.

# Add the encoding argument
with open('my_unicode_file.txt', 'w', encoding='utf-8') as f:
    f.write("Hello with an accent: café. And an emoji: 🐍")

Error Handling (try...except)

What if you don't have permission to write to a directory, or the disk is full? Your program will crash. It's more robust to handle these potential errors.

file_path = 'protected_directory/my_file.txt'
text = "This might fail."
try:
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(text)
except IOError as e:
    # This block runs if an IOError occurs (e.g., file not found, permission denied)
    print(f"Error: Could not write to file. {e}")
except Exception as e:
    # A general catch-all for other unexpected errors
    print(f"An unexpected error occurred: {e}")
else:
    # This block runs ONLY if the 'try' block completed successfully
    print("File written successfully!")

Summary: Which Method to Use?

Your Goal Recommended Method Mode
Write new text to a file, overwriting any existing content. with open(...) as f: f.write(...) 'w'
Add new text to the end of an existing file. with open(...) as f: f.write(...) 'a'
Write a list of lines to a file. with open(...) as f: f.writelines(...) 'w' or 'a'
Always remember to use encoding='utf-8' for any text file.
分享:
扫描分享到社交APP
上一篇
下一篇