Python 2.7如何在主文本生成后向文件指定行插入文本?
Absolutely feasible! Here's how you can adjust your workflow to add that extra text at the target line once all your main content is written:
First, Keep Your Existing Write Logic
Start with your current code to generate and write the full text_to_write to the file. I’ll include a quick example of what text_to_write might look like for context:
import codecs # Your existing process to generate text_to_write goes here text_to_write = "\n".join([f"Line {i}" for i in range(1, 12)]) # Example: 11 lines of sample text # Write the main content to the file outfile = codecs.open("c:/temp/myfile.sps", "w+", "utf-8-sig") outfile.write(text_to_write) outfile.close()
Then, Add the Insertion Code
Once the main content is saved, you’ll read the entire file, insert your extra text at the desired line, and overwrite the file with the modified content. Here’s the implementation:
# Define your target line (1-based numbering) and the text to insert target_line = 10 extra_text = "This is the extra text inserted at line 10\n" # Read all lines from the file into a list with codecs.open("c:/temp/myfile.sps", "r", "utf-8-sig") as f: lines = f.readlines() # Insert the text (convert to 0-index since Python lists start at 0) lines.insert(target_line - 1, extra_text) # Write the updated lines back to the file with codecs.open("c:/temp/myfile.sps", "w", "utf-8-sig") as f: f.writelines(lines)
Key Notes to Remember:
- Line Indexing: If you’re thinking in 1-based terms (like "the 10th line"), subtract 1 to get the correct index for Python’s list
insert()method (since lists are 0-indexed). withStatements: Usingwithfor file operations is better practice—it automatically closes the file, so you don’t have to remember to callclose()manually and avoid resource leaks.- Large Files: If your file is extremely large, reading all lines into memory might not be ideal. For those cases, you could read the file line by line and write to a temporary file, then replace the original with the temp file. But for most standard use cases, the above method is simple and effective.
Quick Alternative (Skip Closing the File)
If you don’t want to close and reopen the file right away, you could seek to the start after writing, read the content, modify it, then write back—but this can get messy with overwriting. The approach above is cleaner and easier to debug.
内容的提问来源于stack exchange,提问作者horace_vr

