几周前,我正在打印“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,只有左边的输出是正确的
什么我错过了吗?有一个更好的方法吗?
嗯,所以我没有真正解决您的问题。你的代码究竟有什么问题,你想在输出中有什么不同? – Salo
啊,现在,对不起,因为愚蠢。我现在明白了这个问题 – Salo
您必须修复缩进。这是“kaputt”,所以不可能理解属于哪里。 – Psytho