2016-08-08 48 views
2

我想讀取特定目錄下的所有文件的內容。我發現如果路徑名不是以/結尾,那麼我的代碼將不起作用(將會產生I/O異常,因爲pathName+f無效 - 在中間缺少/)。下面是一個代碼示例,以顯示它工作時,當它不工作,優雅的方式來檢查Python 2.7中有效的文件目錄路徑

實際上,我可以檢查如果pathname採用的endsWith與/結束,如果更優雅的解決方案,只是不知道什麼時候一個全名串連路徑和文件名?

我的要求是,我想給輸入pathName更靈活,以\結尾,而不是以\結束。

使用Python 2.7。

from os import listdir 
from os.path import isfile, join 

#pathName = '/Users/foo/Downloads/test/' # working 
pathName = '/Users/foo/Downloads/test' # not working, since not ends with/ 
onlyfiles = [f for f in listdir(pathName) if isfile(join(pathName, f))] 
for f in onlyfiles: 
    with open(pathName+f, 'r') as content_file: 
     content = content_file.read() 
     print content 
+6

爲什麼你同時使用'os.path.join(pathName,f)'和'pathName + f'? – Blender

+0

感謝@Blender,投票。 –

回答

3

你只想用再次加入:

pathName = '/Users/foo/Downloads/test' # not working, since not ends with/ 
onlyfiles = [f for f in listdir(pathName) if isfile(join(pathName, f))] 
for f in onlyfiles: 
    with open(join(pathName, f), 'r') as content_file: 
     content = content_file.read() 
     print content 

或者你可以使用水珠忘記加入:

from glob import glob 

pathName = '/Users/foo/Downloads/test' # not working, since not ends with/ 

onlyfiles = (f for f in glob(join(pathName,"*")) if isfile(f)) 

for f in onlyfiles: 
    with open(f, 'r') as content_file: 

或過濾器結合起來的一個更簡潔的解決方案:

onlyfiles = filter(isfile, glob(join(pathName,"*"))) 
+0

它的工作原理,感謝Padraic!投票並標記爲答案。 –

+0

@LinMa,不用擔心,不客氣。 –

+0

@ray,感謝您的編輯。 –

相關問題