2011-02-14 78 views
1

我有一個日誌文件,並在日誌中,有些文件有錯誤,所以當一個文件有錯誤時,我想讀取它的名字(包括路徑)並將它移動到另一個目錄。shutil.move問題 - 額外的

我可以正確讀取輸入文件,例如其中一個文件是:C:\ test \ test1我可以找到該文件,我只想移動它。但是,當我使用shutil.move(filename,another_directory)時,即使打印文件名顯示爲c:\ test1 \ test1,shutil也會在每個斜槓前添加一個額外的'\'..即它試圖移動C:\\ test1 \\ TEST1。 [Shutil.move通過在每個現有'\'中添加額外'\'來誤讀輸入路徑]

我該如何解決?謝謝 !

import shutil 
f=open("test_logs") 
o=open("output_logs","w") 
e=open("error_logs",'w') 

another_directory= "C:/test" 
for line in f: 
    if line.lstrip().startswith("C:"): 
     filename = line 
     #print line 
     #look for errors in the next line onwards. 
    if line.startswith("error"): 
     e.write(filename + "\n") 
     print filename 
     shutil.move(filename,another_directory) 
f.close() 
o.close() 

這是錯誤我得到 - IO錯誤:[錯誤2]沒有這樣的文件或目錄:「C:\\測試\\ TEST1(該文件是C:\測試\ TEST1)和打印文件名顯示c:\ test \ test1

+0

難道這可能是你忘記逃避`another_directory`中的反斜槓嗎? – Santa 2011-02-14 20:48:19

+0

錯誤是當它通過輸入日誌文件(名稱爲c:\ test1 \ test)時,print filename正確地將輸出顯示爲C:\ test1 \ test,但我得到一個錯誤,說沒有這樣的文件或目錄C「 \\ test1 \\ test from shutil command。 – Illusionist 2011-02-14 20:49:18

回答

1

這裏有幾件事情是錯誤的。


從你編輯的錯誤信息,我看你是移動C:/測試/ TEST1到C:/測試/ test1的...這會(如果我沒記錯的話)總是在Windows上失敗。嘗試一個不同的目標目錄進行測試。


another_directory = "C:\test" 

應該是 「C:/測試」 或使用os.path.join等


for line in f: 
    if line.lstrip().startswith("C:"): 
     filename = line 
     #print line 
    if line.startswith("error"): 
     e.write(filename + "\n") 
     print filename 
     shutil.move(filename,another_directory) 

這兩種如果條件不能同時爲真,所以你必須從前面的行解析文件名,然後在後面的行中檢查「錯誤」。但是,line.lstrip()不會修改行,它只會返回一個新值。當您將保存的值(文件名)寫入錯誤日誌時,您有兩條換行符 - 一條仍在文件名中。然後,當你移動該文件時,它不存在,因爲「文件名」仍然具有換行符和任何你跳過的前導空格。


another_directory= "C:/test" 
filename = None 
for line in f: 
    if line.lstrip().startswith("C:"): 
    filename = line.strip() # Remove both leading and trailing WS. 
    print "File:", filename, "(exists: %s)" % os.path.exists(filename) 
    elif line.startswith("error"): 
    assert filename is not None # Do a sanity check as required. 
    e.write(filename + "\n") 
    print "Moving %s..." % filename 
    shutil.move(filename, another_directory) 
0

從文檔上shutil.move

If the destination is on the current filesystem, then simply use rename. Otherwise, copy src (with copy2()) to the dst and then remove src.

...在這種情況下,要使用os.rename因爲這兩個文件確確實實住在同一個文件系統上。相反的:

shutil.move(filename,another_directory) 

務必:

directory, name = os.path.split(filename) 
os.rename(filename, os.path.join('c:', 'test', name)) 

從錯誤信息您收到,我們可以推測shutil.move失敗,因爲它預期目標文件已經存在,它沒有。