用Python重命名文件
问题描述:
几周前,我正在打印“Hello,World”。现在我正在头脑中潜入编码池,我不知道如何游泳。请给我一个救生衣。用Python重命名文件
我有一个目录多个文件,如:
123456 C01-1-File.pdf
123456 C02-1-File.pdf
123456 C02-2- File.pdf
,并希望取消固定,6位前缀和增加增量的前缀,如:
600 -
601 -
602 -
因此,应将文件重命名为:
600 - C01-1-File.pdf
601 - C02-1-File.pdf
602 - C02-2-File.pdf
这是我拼凑起来的脚本:
import os
import glob
import sys
def fileRename():
#this section determines file types to work with based on user input
path = os.getcwd()
a = raw_input('Enter the file extension: ')
b = '*' + '.' + str(a)
first_lst = sorted(glob.glob(b))
l = len(first_lst)
if l > 1:
print 'There are ' + str(l) + ' files of the specified type in the current directory'
elif l == 1:
print 'There is ' + str(l) + ' file of the specified type in the current directory'
else:
print 'There are no files of the specified type in the current directory'
sys.exit()
for file in first_lst:
print '\t' + file
#this section removes a numerical prefix from specified file type
x = raw_input('Would you like to remove the prefix from these files? [y/n]: ')
if x == 'y':
for filename in first_lst:
new_filename = filename
#while filenames in the list start with a number, remove the number
while new_filename[0].isdigit():
new_filename = new_filename[1:]
#rename all files that have had the numerical prefix removed
if new_filename != filename:
print 'Renaming %s to %s' % (filename, new_filename)
os.rename(os.path.join(path,filename), os.path.join(path,new_filename))
xx = raw_input('Would you like to add an iterative prefix to these files? [y/n]: ')
if xx == 'y':
second_lst = sorted(glob.glob(b))
#this creates an iterative list of new prefix numbers
x = int(raw_input('Enter the beginning prefix number: '))
working_lst = range(x, x + l)
prefix_lst = working_lst[:l]
#this combines the prefix list and filename list
final_lst = ['{} -{}'.format(x,y) for x, y in zip(prefix_lst,second_lst)]
for new in final_lst:
print ('Here are the new file names: ')
print '\t' + new
#THIS IS THE SECTION THAT DOES NOT WORK
#this section should rename the files with an iterative prefix
third_lst = sorted(glob.glob(b))
user_input = raw_input('Would you like to continue with renaming? [y/n]: ')
if user_input == 'y':
for file in file_list:
print file
for i in final_list:
print i
print 'Renaming %s to %s' % (file, i)
else: sys.exit()
fileRename()
我玩过的语法和缩进,这将产生以下结果。我遇到的问题是在“你想继续重命名?”之后的输出。
这里有一些照片,显示输出:
在attempt1,只有右侧的输出是正确的
在attempt2,只有左边的输出是正确的
什么我错过了吗?有一个更好的方法吗?
答
好吧我试图修复你的缩进,并发现一些设计上的缺陷。
删除前缀时,可能是您将所有文件重命名为相同的名称。这意味着当你例如将文件
1.jpg
,2.jpg
和3.jpg
全部重命名为.jpg
,因此除重命名后的最后一个文件外,所有文件都不再存在!它在代码中变得非常复杂,主要来自于选择较差的变量名称(如
x
和xx
)以及不使用帮助函数。试着写的辅助函数只做一两件事,并明智地为它们命名:)
因此,这里是重构的结果和清理,我觉得还是做(至少几乎)你想要什么。所以尽量把它当成首发。
import glob
import sys
def fileRename():
# this section determines file types to work with based on user input
a = raw_input('Enter the file extension: ')
b = '*' + '.' + str(a)
first_lst = sorted(glob.glob(b))
l = len(first_lst)
if l > 1:
print('There are ' + str(l) +
' files of the specified type in the current directory')
elif l == 1:
print('There is ' + str(l) +
' file of the specified type in the current directory')
else:
print('There are '
'no files of the specified type in the current directory')
sys.exit()
for file in first_lst:
print '\t' + file
# this section removes a numerical prefix from specified file type
remove_prefix = raw_input('Would you like '
'to remove the prefix from these files? [y/n]: ')
new_filenames = []
if remove_prefix == 'y':
for filename in first_lst:
# while filenames in the list start with a number, remove the number
new_filename = remove_leading_number(filename)
# rename all files that have had the numerical prefix removed
if new_filename != filename:
print 'Renaming %s to %s' % (filename, new_filename)
new_filenames.append(new_filename)
if remove_prefix == 'n':
new_filenames = first_lst
add_counter = raw_input('Would you like to add an '
'iterative prefix to these files? [y/n]: ')
if add_counter == 'y':
# this creates an iterative list of new prefix numbers
prefix_num_start = int(raw_input('Enter the beginning prefix number: '))
prefix_lst = range(prefix_num_start, prefix_num_start + l)
# this combines the prefix list and filename list
final_lst = ['{}-{}'.format(x, y) for x, y in zip(prefix_lst, new_filenames)]
for new in final_lst:
print ('Here are the new file names: ')
print '\t' + new
# THIS IS THE SECTION THAT DOES NOT WORK
# this section should rename the files with an iterative prefix
user_input = raw_input('Would you like to continue with renaming? [y/n]: ')
if user_input == 'y':
for i in final_lst:
print i
print 'Renaming %s to %s' % (file, i)
else:
sys.exit()
def remove_leading_number(filename):
while filename[0].isdigit():
filename = filename[1:]
return filename
fileRename()
快乐编码!
嗯,所以我没有真正解决您的问题。你的代码究竟有什么问题,你想在输出中有什么不同? – Salo
啊,现在,对不起,因为愚蠢。我现在明白了这个问题 – Salo
您必须修复缩进。这是“kaputt”,所以不可能理解属于哪里。 – Psytho