[英]Script to rename and copy files to a new directory.
嗨,我最近使用此腳本重命名了我掃描的帶有前綴和日期的工作文件。 它工作得很好,但是如果可以在當前目錄中創建一個與第一個文件同名的目錄,然后將所有掃描的文件移到該目錄中,那將是很好的。 例如,第一個文件被重命名為“ Scanned As At 22-03-2012 0”,然后一個目錄名為“ Scanned As At 22-03-2012 0”(路徑為M:\\ Claire \\ Scanned As 22-03-2012 0)並將該文件放置在其中。
我很難找到最好的方法來做到這一點。 提前致謝!
import os
import datetime
#target = input( 'Enter full directory path: ')
#prefix = input( 'Enter prefix: ')
target = 'M://Claire//'
prefix = 'Scanned As At '
os.chdir(target)
allfiles = os.listdir(target)
count = 0
for filename in allfiles:
t = os.path.getmtime(filename)
v = datetime.datetime.fromtimestamp(t)
x = v.strftime( ' %d-%m-%Y')
os.rename(filename, prefix + x + " "+str(count) +".pdf")
count +=1
不太清楚您的要求。 如果不重命名文件,只需將其放在目錄下,則可以使用以下代碼(僅示例中的for循環):
for filename in allfiles:
if not os.isfile(filename): continue
t = os.path.getmtime(filename)
v = datetime.datetime.fromtimestamp(t)
x = v.strftime( ' %d-%m-%Y')
dirname = prefix + x + " " + str(count)
target = os.path.join(dirname, filename)
os.renames(filename, target)
count +=1
您可以檢查help(os.renames)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.