幾周前,我正在打印「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