I was creating a simple python script that iterates through files in a directory and changes the names of the files based on a num
variable that increases by one after each iteration.
Here is the code used, with the directory and files involved.
import os
directory = 'JAN'
num = 1
for filename in os.listdir(directory):
f = os.path.join(directory, filename)
new_f = f'JAN-{num}.txt'.format(num=num)
if os.path.isfile(filename):
os.rename(filename, new_f)
num = 1
print(new_f)
Current Files
├── _JAN
│ ├── first.txt
│ ├── second.txt
│ ├── third.txt
│ └── fourth.txt
Desired Changes to Files
├── _JAN
│ ├── JAN-1.txt
│ ├── JAN-2.txt
│ ├── JAN-3.txt
│ └── JAN-4.txt
I have tried a few iterations and the only output received is each new file name printed to the console with no changes to the file names within the JAN
directory.
Any help would be much appreciated.
CodePudding user response:
Like the comments say, you need to check for f not filename and you also need to save it to the dir:
import os
directory = 'JAN'
num = 1
for filename in os.listdir(directory):
f = os.path.join(directory, filename)
new_f = os.path.join(directory, f'JAN-{num}.txt'.format(num=num))
if os.path.isfile(f):
os.rename(f, new_f)
num = 1
print(new_f)
You can also use enumerate instead of num:
for i, filename in enumerate(os.listdir(directory), 1):
f = os.path.join(directory, filename)
new_f = os.path.join(directory, f'JAN-{i}.txt')
if os.path.isfile(f):
os.rename(f, new_f)
print(new_f)
CodePudding user response:
additional note: there is no need to use .format
when you use f''
already.
import os
directory = 'JAN'
num = 1
os.chdir(directory) # Changes current working directory to "JAN"
for filename in os.listdir(): # equals to: for filename in current directory.
new_f = f'{directory}-{num}.txt'
if os.path.isfile(filename): # now it can detect filename since we've changed the current working directory.
os.rename(filename, new_f)
num = 1
CodePudding user response:
Have a look to os.scandir
. It's an iterator whose object are os.DirEntry
instances which make them easy to work with (have attributes such as name
, path
, is_file
, ...), in particular you can bypass the side-effect of listdir
that returns basenames and not paths.
Here assumed that the files are already in the right order in the directory.
import os
directory = 'JAN'
new_f_template = os.path.join(directory, 'JAN-{}.txt')
with os.scandir(directory) as files:
for i, f in enumerate(files, 1):
if f.is_file():
new_f = new_f_template.format(i)
os.rename(f.path, new_f)
print(f"{f.name} -> {new_f}")