Python文件指定行修改后无法写入文件的问题求助
Fixing the File Write Issue in Your Line-Editing Python Script
Let's break down what's going wrong in your code and fix it step by step.
First, the core issue in your current script is the redundant inner loop and a minor confusion with what you're printing. While your code does modify the filedata list, the print statement is showing you the original line (not the modified one), which might have led you to think the changes weren't being written. Plus, that inner loop is unnecessary and could introduce unexpected behavior if you're not careful.
Here's the revised version of your code with key fixes and improvements:
import os def editPicReplace(): source_folder = "/path/to/your/folder" # Replace with your actual folder path for somefile in os.listdir(source_folder): file_path = os.path.join(source_folder, somefile) # Skip directories to avoid errors if not os.path.isfile(file_path): continue # Read the file content with open(file_path, "r") as file: filedata = file.readlines() # Collect indices of lines starting with your target string index_list = [] for index, line in enumerate(filedata): if line.startswith(' picture "TR_NAME_XF"'): index_list.append(index) print(f"Found target lines in {somefile} at indices: {index_list}") # Modify the line 7 positions after each target index for a in index_list: target_index = a + 7 # Prevent index out of range errors if target_index >= len(filedata): print(f"Warning: Cannot modify line {target_index} in {somefile} - file is too short!") continue original_line = filedata[target_index] # Apply your replacement logic modified_line = original_line[:18].replace('2', '') + original_line[18:] filedata[target_index] = modified_line # Print the actual change for verification print(f"Modified line in {somefile}:") print(f"Original: {repr(original_line)}") print(f"Updated: {repr(modified_line)}") # Write the modified content back to the file with open(file_path, "w") as file: file.write("".join(filedata)) print(f"Successfully saved changes to {somefile}\n")
Key Changes Explained:
- Removed the redundant inner loop: You already know exactly which index to modify (
a + 7), so there's no need to loop through the entire file again. This makes the code faster and avoids accidental re-modifications. - Fixed the print statement: Now we print both the original and modified lines, so you can confirm the change is actually happening. Using
repr()helps show hidden characters like newlines too. - Added index safety check: Prevents crashes if
a + 7goes beyond the number of lines in the file. - Skipped directories: Avoids trying to read folders as files, which would throw an error.
- Simplified file path handling: Stored the full file path in a variable to make the code cleaner.
Additional Checks to Ensure Writes Work:
- Verify folder path: Double-check that
source_folderpoints to the correct directory where your target files are located. - File permissions: Make sure your script has write access to the files and folder. On Linux/macOS, you might need to run the script with
sudoif the files are in a protected directory. On Windows, ensure the files aren't open in another program (which would lock them from being modified). - Check for hidden files: If
os.listdir()is picking up hidden files you don't intend to modify, you can add a check to skip them (e.g.,if somefile.startswith('.'): continue).
内容的提问来源于stack exchange,提问作者Ninjasoup
相关产品推荐
相关产品推荐

