You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python操作现有文本文件:向行添加字符及为行加序号的方法

Hey there! Let's break down your questions one by one—they're all about Python file handling, which is super common when working with text files.

1. Adding characters to existing lines in a text file

You can't directly modify lines in place in a text file (most operating systems don't support that). The standard workflow is:

  • Read all the content from the file
  • Modify each line as needed
  • Write the modified content back to the file (or a new file, then replace the original if you want to keep a backup)

Here's a quick example that adds a prefix like [EDIT] to every line:

# Read the original file
with open("your_file.txt", "r") as f:
    lines = f.readlines()

# Modify each line
modified_lines = [f"[EDIT] {line}" for line in lines]

# Write back to the file (overwrites original)
with open("your_file.txt", "w") as f:
    f.writelines(modified_lines)

Using with statements is a best practice because it automatically closes the file for you, avoiding resource leaks.

2. Adding line numbers to each line (e.g., 1.apple, 2.banana)

Absolutely! This is just a specific case of adding characters to lines. You can use enumerate() to get both the line number and the line content. Just make sure to start counting from 1 instead of the default 0.

Example code:

# Read the original file (assuming it's named fruits.txt)
with open("fruits.txt", "r") as f:
    lines = f.readlines()

# Add line numbers—strip any extra newlines first to avoid double line breaks
modified_lines = [f"{idx}.{line.strip()}\n" for idx, line in enumerate(lines, start=1)]

# Write back to the file
with open("fruits.txt", "w") as f:
    f.writelines(modified_lines)

If your file is very large (like hundreds of thousands of lines), you might want to process it line by line instead of loading everything into memory. You can do this by reading from the original file and writing to a temporary file, then replacing the original once done.

3. Fixing your number-writing code

You're right about the issue: the write() method only accepts string type arguments, but i is an integer from range(14). You just need to convert i to a string with str(i). Also, your original code doesn't close the file explicitly—using with fixes that automatically.

Here's the corrected code:

with open("dates.txt", "a") as myfile:
    for i in range(14):
        # Convert integer to string before writing
        myfile.write(str(i) + "\n")

Note: range(14) will write numbers 0 to 13. If you want 1 to 14 instead, use range(1, 15) instead.

Hope these solutions help you out—file handling gets way easier once you get the hang of the read-modify-write workflow! 😊

内容的提问来源于stack exchange,提问作者newbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:06:02