N
N
Nikcet2020-12-09 17:51:25
Python
Nikcet, 2020-12-09 17:51:25

(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, '- Старый вариант этого файла уже существует.')

After that comes the file creation code.

The problem is that this script only runs once . The second time always throws an exception. The names of the old renamed files and the new names for the new files do NOT match . The contents of old files and new ones are also always different .

Why is there no renaming for newly created files?

Ps Files are created using the operation
with open("fileName.txt", "w", encoding="utf8") as data_file: 
...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dr. Bacon, 2020-12-09
@bacon

And the error says it matches, learn to debug, well, or add a new name to print to see the problematic one.

_
_, 2020-12-09
@mrxor

Your time is rounded to minutes when forming the name of the old file. Launched more often - got an error.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question