简体   繁体   English

根据一个txt文件的内容重命名一个目录下的所有文件

[英]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第1行
  • line2线2
  • line3第 3 行

And a folder with the same number of of .png files as lines in the text file.以及与文本文件中的行数相同的.png文件的文件夹。

I'm trying to rename the .png files based on the corresponding line in the text file.我正在尝试根据文本文件中的相应行重命名.png文件。 ie .png one = line1 in the text file and so on.即文本文件中的.png one = line1等等。

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循环遍历每个.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').我可以使用glob获取文件名,打开文本文件并使用readlines读取行,我可以使用os.rename重命名文件,使用strip()删除行尾字符('\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?如何根据文本文件的内容重命名.png文件?

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.打开文本文件(不需要readlines,你可以直接循环f ),并在重命名时与zip的png文件一起逐行迭代。

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只需更改current_folder变量以反映您正在使用的内容

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())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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