【发布时间】:2016-01-01 20:37:44
【问题描述】:
几周前,我正在打印“Hello, World”。现在我一头扎进编码池,我不会游泳。请给我一个救生圈。
我在一个目录下有几个文件,比如:
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中,只有左边的输出是正确的
我错过了什么?有一个更好的方法吗?
【问题讨论】:
-
嗯,所以我真的不明白你的问题。您的代码到底有什么问题,您希望输出有什么不同?
-
啊,对不起,我很愚蠢。我现在明白这个问题了
-
你必须修复缩进。它是“kaputt”,因此无法理解什么属于哪里。
标签: python list rename file-rename renaming