简体   繁体   中英

Rename all files in a directory based on the content of a txt file

I've a text file with a few thousand lines in it:

  • line1
  • line2
  • line3

And a folder with the same number of of .png files as lines in the text file.

I'm trying to rename the .png files based on the corresponding line in the text file. ie .png one = line1 in the text file and so on.

I figure I need to do three different things:

  1. Read the text file to generate a list storing the names
  2. Loop over each .png
  3. Rename it based on the list enumeration

I can grab the file names with glob , and open the text file and read the lines with readlines and I can rename files with os.rename using strip() to remove the end-of-line character ('\n').

path_to_images = glob.glob(r"C:\test*.png")

with open('names.txt') as f:
    lines = f.readlines()

os.rename(filename, firstline.strip())

What I'm struggling with is how to combine these three pieces into code that actually works.

How do I rename my .png files based on the contents of the text file?

Open the textfile (no need for readlines, you can directly loop through f ) and iterate together with the png files with zip line by line while renaming.

path_to_images = glob.glob(r"C:\test*.png")

with open('names.txt') as f:
    for line, file in zip(f, path_to_images):
        os.rename(file, line.strip())

This code should do what you need. Note I've put the folders based on where my files are. Just change the current_folder variable to reflect what you're using

import glob
import os

current_folder = os.path.abspath('.') + '\\rename_files\\'
file_path = current_folder +  'files_to_rename.txt'

with open(file_path, 'r') as f:
    for file in list(glob.glob(current_folder + '*.png')):        
        os.rename(file, current_folder + f.readline().strip())

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