如何用Python实现文本文件指定行数剪切粘贴并删除原复制行?
Hey there! Let's fix this problem properly—you want to cut (copy + delete) a specific number of lines from one text file to another, right? Your current code only handles the copying part, so let's fill in the missing piece (deleting the copied lines from the source file) and clean things up.
First, Let's Break Down Your Current Code's Limitations
Your existing code copies the first 63 lines from try3.txt to try4.txt, but it doesn't modify the source file to remove those lines. Also, the while loop doesn't serve any real purpose here, and you're opening the source file in read-only mode ('r'), which prevents edits.
The Fix: A Complete Cut-and-Paste Function
Here's a straightforward approach that reads the source file, splits its content into the lines you want to cut and the remaining lines, appends the cut lines to the target file, and overwrites the source file with the remaining lines.
def cut_lines(source_file, target_file, num_lines): # Step 1: Read all lines from the source file with open(source_file, 'r') as f: all_lines = f.readlines() # Step 2: Split lines into those to cut and those to keep lines_to_cut = all_lines[:num_lines] remaining_lines = all_lines[num_lines:] # Step 3: Append cut lines to the target file with open(target_file, 'a') as f_target: f_target.writelines(lines_to_cut) # Step 4: Overwrite source file with remaining lines (deletes the cut lines) with open(source_file, 'w') as f_source: f_source.writelines(remaining_lines) # Example usage: Cut first 63 lines from try3.txt to try4.txt cut_lines("try3.txt", "try4.txt", 63)
Key Details to Note:
readlines(): Reads all lines of the source file into a list, making it easy to split into two parts.- Slicing:
all_lines[:num_lines]grabs the firstnum_lineslines (the ones to cut), whileall_lines[num_lines:]takes everything after that (the lines to keep). - File Modes:
'a'for the target file appends the cut lines instead of overwriting existing content.'w'for the source file overwrites it with only the remaining lines—this is how we "delete" the cut lines from the source.
- Safety Tip: Always back up your source file before running this, just in case you accidentally cut more lines than intended!
Handling Edge Cases (Optional)
If you want to make the function more robust, add checks for things like:
- The source file not existing
- The source file having fewer lines than
num_lines(in which case we'll cut all lines, leaving the source file empty)
Here's an enhanced version with error handling:
def cut_lines_safe(source_file, target_file, num_lines): try: with open(source_file, 'r') as f: all_lines = f.readlines() # If source has fewer lines than requested, cut all of them lines_to_cut = all_lines[:num_lines] remaining_lines = all_lines[num_lines:] with open(target_file, 'a') as f_target: f_target.writelines(lines_to_cut) with open(source_file, 'w') as f_source: f_source.writelines(remaining_lines) print(f"Successfully cut {len(lines_to_cut)} lines from {source_file} to {target_file}") except FileNotFoundError: print(f"Error: The source file {source_file} doesn't exist!") except Exception as e: print(f"An unexpected error occurred: {str(e)}") cut_lines_safe("try3.txt", "try4.txt", 63)
内容的提问来源于stack exchange,提问作者Silviu1994

