我有一个包含多个文件的目录。 文件名称遵循这种模式4digits.1.4digits。[条形码] 条形码指定每个文件,它由7个字母组成。 我有一个txt文件,其中一列中有条形码,另一列是文件的真实名称。 我想要做的是正确的pyhthon脚本,根据条形码自动重命名每个文件,它是写在txt文件中的新名称。Python3将文件重命名为从txt文件导入新名称的目录
有没有人可以帮助我?
非常感谢!
我有一个包含多个文件的目录。 文件名称遵循这种模式4digits.1.4digits。[条形码] 条形码指定每个文件,它由7个字母组成。 我有一个txt文件,其中一列中有条形码,另一列是文件的真实名称。 我想要做的是正确的pyhthon脚本,根据条形码自动重命名每个文件,它是写在txt文件中的新名称。Python3将文件重命名为从txt文件导入新名称的目录
有没有人可以帮助我?
非常感谢!
下面的代码将为您的具体使用情况做这项工作,但可以使它更通用的重新命名。
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
我会给你的逻辑:
读取包含条形码和名称的文本文件。 http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python。
在txt文件的每一行如下操作:
2.分配在两个分开的变量在第一(条形码)第二(名称)列中的值,并说“B”和“N”。
3.现在我们必须找到其中有条形码'B'的文件名。链接 Find a file in python将帮助你做到这一点。(第一个答案,第三例如,对于你的情况,你会发现会像“* B”的名称)
4.上一步会给你具有B作为一部分的文件名。现在使用rename()函数将文件重命名为'N'。这个链接会帮你。 http://www.tutorialspoint.com/python/os_rename.htm
建议:而不是有两列的txt文件。你可以有一个csv文件,这将很容易处理。
与你的例子更精确和格式化你的问题说清楚了“视觉”的人,请:) –