Код: Выделить всё
in WordSwap
with open(FilePath, "w", encoding="utf-8") as file:
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\user\\Documents\\First_folder\\Second_folder\\filename.blk'
Код: Выделить всё
import os
def WordSwap(FolderPath):
# Check if the provided folder exists
if not os.path.isdir(FolderPath):
print(f"Error: '{FolderPath}' is not a valid directory.")
return
# Loop through all files in the folder
for filename in os.listdir(FolderPath):
if filename.lower().endswith(".blk"):
FilePath = os.path.join(FolderPath, filename)
# Read file Contents
with open(FilePath, "r", encoding="utf-8") as file:
Content = file.read()
# Replace all occurrences of WORD with NEWWORD
CorrectedContent = Content.replace("WORD", "NEWWORD")
# Only write if there was a change
if CorrectedContent != Content:
# Make a backup before overwriting
BackupPath = FilePath + ".bak"
with open(BackupPath, "w", encoding="utf-8") as BackupFile:
BackupFile.write(Content)
# Write the updated Content back to the file
with open(FilePath, "w", encoding="utf-8") as file:
file.write(CorrectedContent)
print(f"Updated: {filename} (backup created: {BackupPath})")
else:
print(f"No 'WORD' found in: {filename}")
print("\nDone! All .blk files processed.")
if __name__ == "__main__":
folder = r"C:\Users\user\Documents\First_folder\Second_folder"
WordSwap(folder)
Подробнее здесь: https://stackoverflow.com/questions/798 ... rite-files
Мобильная версия