2012-05-08 81 views
14

我是python和編碼的新手。我正嘗試從每行上都有路徑名的文本文件讀取。我想逐行閱讀文本文件,並將行字符串拆分爲驅動器,路徑和文件名。將路徑字符串拆分爲驅動器,路徑和文件名部分

這裏是我的代碼至今:

我得到以下錯誤:

File "C:/Users/visc/scratch/simple.py", line 14, in <module> 
    (drive,path,file) = os.path.split(line) 
ValueError: need more than 2 values to unpack 

我沒有收到這個錯誤時,我只希望的路徑和文件名。

回答

23

您需要使用os.path.splitdrive第一:

with open('C:/Users/visc/scratch/scratch_child/test.txt') as f: 
    for line in f: 
     drive, path = os.path.splitdrive(line) 
     path, filename = os.path.split(path) 
     print('Drive is %s Path is %s and file is %s' % (drive, path, filename)) 

注:

  • with聲明可以確保文件在該塊結束時關閉(文件後,也會關閉時垃圾收集器吃掉它們,但使用with通常是很好的做法
  • 你不需要使用方括號ETS - os.path.splitdrive(路徑)返回一個元組,而這將讓自動解壓縮
  • file是標準命名空間類的名字,你可能不應該覆蓋它:)
+0

您好,我收到以下輸出:驅動器是路徑是「S:\ Entourage \ GIS \ HemloBelt \ Claims和文件是Entourage_Claims_Master.shp」,所以不是我所期望的。每行都格式化如下:「S:\ Entourage \ GIS \ HemloBelt \ Claims \ Entourage_Claims_Master.shp」, – Visceral

+0

我想你是在一臺Windows機器上。在'drive,path = ...'之前,添加'line = line.replace(「\\」,「/」)'用正斜槓替換反斜槓,看看這是否有效。 –

+0

我發現它爲什麼表現得如此。我在原始文本文件中引用了每行字符串的引號。 – Visceral

3

您可以使用os.path.splitdrive()獲取驅動器,然後使用path.split()其餘部分。

## Open the file with read only permit 
f = open('C:/Users/visc/scratch/scratch_child/test.txt') 

for line in f: 
    (drive, path) = os.path.splitdrive(line) 
    (path, file) = os.path.split(path) 

    print line.strip() 
    print('Drive is %s Path is %s and file is %s' % (drive, path, file)) 
+0

感謝花時間回答。 – Visceral

+0

嗨Jordanm,這是我的屏幕上打印的:'code'「S:\ Entourage \ GIS \ HemloBelt \ Claims \ Entourage_Claims_Master.shp」, Drive is Path is「S:\ Entourage \ GIS \ HemloBelt \ Claims」文件是Entourage_Claims_Master.shp「,不完全是我想到的。 – Visceral