簡體   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