-1
我試圖在Python中使用shutil
模塊移動文件。我不斷收到此錯誤:使用shutil.move移動文件的問題()
Traceback (most recent call last):
File "<input>", line 31, in <module>
File "C:\Python27\lib\shutil.py", line 302, in move
copy2(src, real_dst)
File "C:\Python27\lib\shutil.py", line 130, in copy2
copyfile(src, dst)
File "C:\Python27\lib\shutil.py", line 82, in copyfile
with open(src, 'rb') as fsrc:
IOError: [Errno 2] No such file or directory: 'MLR_Resi_Customer.txt'
我不明白爲什麼我越來越沒有這樣的文件或目錄。如果不使用shutil.move(filename, new_dest)
,它將打印我正在查找的文件名。
import shutil
import os
import datetime
# set location of folders and files needed
source = '//nspinfwcipp01/BSA/marketing'
dest_cust = '//nspinfwcipp01/BSA/marketing/res_cust'
dest_pros = '//nspinfwcipp01/BSA/marketing/res_pros'
dest_win = '//nspinfwcipp01/BSA/marketing/res_win'
# create date time stamp of now
dt = str(datetime.datetime.now())
files = os.listdir(source)
print files
# create new path to storage files for old data
cust_files = os.listdir(dest_cust)
pros_files = os.listdir(dest_pros)
win_files = os.listdir(dest_win)
# new file names
new_cust = 'MLR_Resi_Customers'+dt+'.txt'
new_pros = 'MLR_Resi_Prospects'+dt+'.txt'
new_win = 'MLR_Resi_Winbacks'+dt+'.txt'
#move files from marketing folder into their own folder when after done processing
for f in files:
if (f.endswith("Customer.txt")):
print f
shutil.move(f,dest_cust)
elif (f.endswith("Prospects")):
#print f
shutil.move(f,dest_pros)
elif (f.endswith("Winbacks")):
#print f
shutil.move(f,dest_win)
##rename files in storage with data for Kalyan and Jake's Project
## rename customer file for storage
for x in cust_files:
if (x.endswith("Customers")):
#print x
new_cust = 'MLR_Resi_Customer'+dt+'.txt'
os.rename('MLR_Resi_Customers.txt', new_cust)
else:
print "no_customer_file"
## rename prospect file for storage
for x in cust_files:
if (x.endswith("Prospects")):
#print x
os.rename('MLR_Resi_Prospects.txt', new_pros)
else:
print "no_prospect_file"
## rename winback file for storage
for x in cust_files:
if (x.endswith("Winbacks")):
#print x
os.rename('MLR_Resi_Winbacks.txt', new_win)
else:
print "no_winback_file"
所以我不知道我在做什麼錯。文件的路徑是正確的,它似乎能夠打印文件的名字就好了。任何有關上述問題的幫助將不勝感激。
它可能正在尋找當前工作目錄中的'MLR_Resi_Customer.txt' - 您需要創建一個路徑,其中的基礎連接到源文件的文件名(也可以更好地指定目標,或者使用尾部/或目標文件名)。 –
你可以將其修剪成幾行來展示錯誤的文件副本嗎?這是很多需要查看的代碼。 – tdelaney
'os.listdir()'只返回文件名(它們不包括目錄路徑)。這就是爲什麼你得到文件未找到錯誤。可以使用'os.path.join()'將目錄路徑添加到返回列表中的每個文件名,或者使用'glob.glob()',而不是使用調用的路徑返回文件名(假設您提供了一個)附在它上面。 – martineau