2012-05-10 43 views
2

我想遍歷現有路徑和文件名的文本文件中的每一行,將字符串分爲驅動器,路徑和文件名。那麼我想要做的就是將這些文件的路徑複製到一個新的位置 - 或者是一個不同的驅動器,或者追加到一個現有的文件樹中(即,如果S:\ A \ B \ C \ D \ E \ F.shp是我的原始文件,我希望將它添加到新的位置作爲C:\ users \ visc \ A \ B \ C \ D \ E \ F.shpPython os.makedirs重新創建路徑

由於我的編程能力差,我繼續收到錯誤:

File "C:\Users\visc\a\b.py", line 28, in <module> 
    (destination) = os.makedirs(pathname, 0755); 

這裏是我的代碼:

進口操作系統,SYS,shutil

## Open the file with read only permit 
f = open('C:/Users/visc/a/b/c.txt') 

destination = ('C:/Users/visc') 
# read line by line 
for line in f: 

    line = line.replace("\\\\", "\\") 
    #split the drive and path using os.path.splitdrive 
    (drive, pathname) = os.path.splitdrive(line) 
    #split the path and fliename using os.path.split 
    (pathname, filename) = os.path.split(pathname) 
#print the stripped line 
    print line.strip() 
#print the drive, path, and filename info 
    print('Drive is %s Path is %s and file is %s' % (drive, pathname, filename)) 

    (destination) = os.makedirs(pathname, 0755); 
    print "Path is Created" 

謝謝

+4

您沒有包含實際的錯誤信息。 –

+1

部分追溯?更糟糕的是,根本沒有發佈。 – KurzedMetal

+0

對不起,這裏是我的完整錯誤信息:'Traceback(最近調用最後一個): 文件「C:\ Users \ visc \ a \ b.py」,第28行,在 (destination)= os.makedirs路徑名,0755); mkdir(名稱,模式) WindowsError:[錯誤183]當該文件已存在時,無法創建文件:'\ C:\ Python26 \ ArcGIS10.0 \ lib \ os.py「 \ A \\ B \\ C \\ D \\ E'' – Visceral

回答

3

我猜你想要的東西像

os.makedirs(os.path.join(destination, pathname), 0755) 

,如果你想連接的pathnamedestination給出的新目標給出的文件路徑。你的代碼目前試圖在與之前相同的位置創建一個文件(至少看起來像這樣 - 不能肯定地說,因爲我不知道你正在閱讀的文件和當前目錄是什麼)。

如果分配調用os.makedirs()destination的結果(括號是在該行的分號無用),您可以有效地設置destinationNone因爲os.makedirs()實際上並不返回任何東西。而你並沒有用它來構建你的新路徑。

+0

對不起,這裏是我的完整錯誤信息:'文件「C:\ Users \ visc \ a \ b。(目的地)= os.makedirs(路徑名,0755);文件「C:\ Python26 \ ArcGIS10.0 \ lib \ os.py」,第157行,在makedirs mkdir(name,mode) WindowsError:[錯誤183]該文件已存在時無法創建文件:'\\ A \\ B \\ C \\ D \\ E'' – Visceral

4

您需要做的是在調用makedirs()之前檢查文件夾的存在,或處理髮生在文件夾已存在的異常情況。在Python這是一個有點傳統的處理異常,所以更改makedirs()行:

try: 
    (destination) = os.makedirs(pathname, 0755) 
except OSError: 
    print "Skipping creation of %s because it exists already."%pathname 

試圖創建,它被稱爲「三思而後行」或LBYL前檢查該文件夾的策略;處理預期錯誤的策略是「容易要求寬恕而不是權限」或EAFP。 EAFP的優勢在於,它正確處理了檢查和makedirs()調用之間的另一個進程創建文件夾的情況。

+0

發生錯誤是因爲他在錯誤的位置構建目錄 - 捕獲例外只會掩蓋問題 –

+1

我通常不會屏蔽某個特定類型的所有異常,它會更好地執行此類操作'除了OSError,e:if e.errno!= errno.EEXIST:raise' – btimby

0

的Python 3.2添加了一個exist_ok可選參數:

os.makedirs(名稱,模式= 0o777,exist_ok = FALSE)

如果你有被允許使用Python 3奢華,這可能在更好(和更安全)的選擇。