简体   繁体   中英

Rename files in a directory with incremental index

INPUT: I want to add increasing numbers to file names in a directory sorted by date. For example, add "01_", "02_", "03_"...to these files below.

test1.txt (oldest text file)
test2.txt
test3.txt
test4.txt (newest text file)

Here's the code so far. I can get the file names, but each character in the file name seems to be it's own item in a list.

import os
for file in os.listdir("/Users/Admin/Documents/Test"):
if file.endswith(".txt"):
      print(file)

The EXPECTED results are:

   01_test1.txt
   02_test2.txt
   03_test3.txt
   04_test4.txt

with test1 being the oldest and test 4 being the newest.

How do I add a 01_, 02_, 03_, 04_ to each file name?

I've tried something like this. But it adds a '01_' to every single character in the file name.

new_test_names = ['01_'.format(i) for i in file]
print (new_test_names)
  1. If you want to number your files by age, you'll need to sort them first. You call sorted and pass a key parameter. The function os.path.getmtime will sort in ascending order of age (oldest to latest).

  2. Use glob.glob to get all text files in a given directory. It is not recursive as of now, but a recursive extension is a minimal addition if you are using python3.

  3. Use str.zfill to strings of the form 0x_

  4. Use os.rename to rename your files

import glob
import os

sorted_files = sorted(
    glob.glob('path/to/your/directory/*.txt'), key=os.path.getmtime)

for i, f in enumerate(sorted_files, 1):
    try:
        head, tail = os.path.split(f)            
        os.rename(f, os.path.join(head, str(i).zfill(2) + '_' + tail))
    except OSError:
        print('Invalid operation')

It always helps to make a check using try-except , to catch any errors that shouldn't be occurring.

This should work:

import glob

new_test_names = ["{:02d}_{}".format(i, filename) for i, filename in enumerate(glob.glob("/Users/Admin/Documents/Test/*.txt"), start=1)]

Or without list comprehension:

for i, filename in enumerate(glob.glob("/Users/Admin/Documents/Test/*.txt"), start=1):
    print("{:02d}_{}".format(i, filename))

Three things to learn about here:

  1. glob , which makes this sort of file matching easier.
  2. enumerate , which lets you write a loop with an index variable.
  3. format , specifically the 02d modifier, which prints two-digit numbers (zero-padded).

The easiest way is to simply have a variable, such as i , which will hold the number and prepend it to the string using some kind of formatting that guarantees it will have at least 2 digits:

import os

i = 1
for file in os.listdir("/Users/Admin/Documents/Test"):
  if file.endswith(".txt"):
        print('%02d_%s' % (i, file)) # %02d means your number will have at least 2 digits
        i += 1

You can also take a look at enumerate and glob to make your code even shorter (but make sure you understand the fundamentals before using it).

test_dir = '/Users/Admin/Documents/Test'
txt_files = [file
             for file in os.listdir(test_dir)
             if file.endswith('.txt')]
numbered_files = ['%02d_%s' % (i + 1, file)
                  for i, file in enumerate(txt_files)]

two methods to format integer with leading zero.

1.use .format

import os
i = 1
for file in os.listdir("/Users/Admin/Documents/Test"):
    if file.endswith(".txt"):
        print('{0:02d}'.format(i) + '_' + file)
        i+=1

2.use .zfill

import os
i = 1
for file in os.listdir("/Users/Admin/Documents/Test"):
    if file.endswith(".txt"):
        print(str(i).zfill(2) + '_' + file)
        i+=1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM