Разрешение отклонено при попытке перезаписать файлыPython

Программы на Python
Ответить
Anonymous
 Разрешение отклонено при попытке перезаписать файлы

Сообщение Anonymous »

Мне хотелось бы изменить одно слово во многих файлах .blk. Я использую Питон. Я спросил ChatGPT, но постоянно получаю эту ошибку

Код: Выделить всё

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)
Скрипт Python находится в папке First_folder, и для его запуска я использую Spyder.

Подробнее здесь: https://stackoverflow.com/questions/798 ... rite-files
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Python»