繁体   English   中英

Python3重命名目录中的文件,以从txt文件导入新名称

[英]Python3 Rename files in a directory importing the new names from a txt file

我有一个包含多个文件的目录。 文件名遵循以下格式4digits.1.4digits。[barcode]条形码指定每个文件,由7个字母组成。 我有一个txt文件,其中一栏中有该条形码,另一栏中有该文件的真实名称。 我想做的是纠正一个pyhthon脚本,该脚本会根据条形码自动将每个文件重命名为txt文件中写入的新名称。

有没有人可以帮助我?

非常感谢!

我会给你逻辑:

1.阅读包含条形码和名称的文本文件。 http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python

对于txt文件中的每一行,请执行以下操作:

2.在“ B”和“ N”两个单独的变量中的“ first(条形码)”和“ second(name)”列中分配值。

3.现在,我们必须找到其中带有条形码“ B”的文件名。 链接在python中查找文件将帮助您做到这一点。(第一个答案,第三个示例,对于您而言,要查找的名称将类似于“ * B”)

4.上一步将为您提供包含B的文件名。 现在使用rename()函数将文件重命名为“ N”。 此链接将帮助您。 http://www.tutorialspoint.com/python/os_rename.htm

建议:不要使用两列的txt文件。 您可以使用一个csv文件,该文件很容易处理。

以下代码将针对您的特定用例完成工作,尽管可以使其更通用。

import os # os is a library that gives us the ability to make OS changes

def file_renamer(list_of_files, new_file_name_list):
    for file_name in list_of_files:
        for (new_filename, barcode_infile) in new_file_name_list:
            # as per the mentioned filename pattern -> xxxx.1.xxxx.[barcode]
            barcode_current = file_name[12:19] # extracting the barcode from current filename
            if barcode_current == barcode_infile:
                os.rename(file_name, new_filename)  # renaming step
                print 'Successfully renamed %s to %s ' % (file_name, new_filename)


if __name__ == "__main__":
    path = os.getcwd()  # preassuming that you'll be executing the script while in the files directory
    file_dir = os.path.abspath(path)
    newname_file = raw_input('enter file with new names - or the complete path: ')
    path_newname_file = os.path.join(file_dir, newname_file)
    new_file_name_list = []
    with open(path_newname_file) as file:
        for line in file:
            x = line.strip().split(',')
            new_file_name_list.append(x)

    list_of_files = os.listdir(file_dir)
    file_renamer(list_of_files, new_file_name_list)

假设前提:newnames.txt-逗号

0000.1.0000.1234567,1234567
0000.1.0000.1234568,1234568
0000.1.0000.1234569,1234569
0000.1.0000.1234570,1234570
0000.1.0000.1234571,1234571

1111.1.0000.1234567
1111.1.0000.1234568
1111.1.0000.1234569 

被重命名为

0000.1.0000.1234567
0000.1.0000.1234568
0000.1.0000.1234569

终端输出:

>python file_renamer.py
enter file with new names: newnames.txt
The list of files -  ['.git', '.idea', '1111.1.0000.1234567', '1111.1.0000.1234568', '1111.1.0000.1234569', 'file_renamer.py', 'newnames.txt.txt']
Successfully renamed 1111.1.0000.1234567 to 0000.1.0000.1234567
Successfully renamed 1111.1.0000.1234568 to 0000.1.0000.1234568
Successfully renamed 1111.1.0000.1234569 to 0000.1.0000.1234569

暂无
暂无

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

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