2014-06-16 76 views
0

閱讀文本文件當我使用R,我能讀懂它們包含在一個文件夾一次性許多文本文檔。 但是,我剛開始學習Python。當我使用命令:file = open('c:/txt/Romney', 'r'),試圖打開包含在羅姆尼文件夾中的所有文本文件,我發現我要讀內文用一個文件中的一個,我不能閱讀所有一次性就像我在河做什麼建議嗎?文本挖掘:在Python

+3

你所說的「一次性」是什麼意思?你想連接它們嗎?或者一個一個迭代它們? –

+1

我很好奇R是如何做到的。這種行爲聽起來像R試圖猜測你可能想要做什麼 – MxyL

+1

發佈你試圖在Python中模擬/複製的R代碼會有幫助。 – hrbrmstr

回答

5

在像Python語言,你需要使用一個for循環在時間閱讀每個文件的內容之一。

(相關:How to list all files of a directory in Python

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

path = "C:/txt/Romney" 
files = [ f for f in listdir(path) if isfile(join(path,f)) ] 

for file in files: 
    with open file as f: 
     text = f.read() 
     do_something_with(text) 
2

除了戴夫Yarwood的回答,如果你真正想要做的是串聯的文件,你可以用做:

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

path = "C:/txt/Romney" 
files = [open(f) for f in listdir(path) if isfile(join(path,f))] 

for line in chain(*files): 
    do_something_with(line) 

(只爲了好玩,因爲我從來沒有用過itertools.chain串起來文件之前)

+0

你不應該再對文件的文件做':file.close()'? –

+0

而不會是'[f.open()對於F中...'? –

+0

@DaveYarwood當對象被垃圾收集時,文件會自動關閉。而'listdir'只是返回一個字符串列表,而不是文件句柄。字符串沒有「開放」方法。 –