Answer the question
In order to leave comments, you need to log in
(python) Why is the file not being renamed with os.rename()?
Hello.
I'm doing a practice assignment.
Task: Create multiple files with some content. But if such files already exist, rename the old files (according to the form) and create new ones.
Here is the operation of renaming files:
from os import mkdir, chdir, getcwd, listdir, rename
from datetime import datetime as dt
from os.path import getctime
if len(listdir()) > 0:
for file in listdir():
if not 'old_' in file:
date = dt.fromtimestamp(getctime(file)).strftime('%Y-%m-%dT%H_%M') # <--- Дата создания файла для вставки в название файла
new_name = f"old_{file[:-4]}_{date}.txt" # <--- Текст для нового названия файла
try:
rename(file, new_name) # <--- Переименовывание файла тут
except FileExistsError:
print(file, '- Старый вариант этого файла уже существует.')
with open("fileName.txt", "w", encoding="utf8") as data_file:
...
Answer the question
In order to leave comments, you need to log in
And the error says it matches, learn to debug, well, or add a new name to print to see the problematic one.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question