2014-12-18 138 views
0

我需要一點幫助來完成我的程序。 我在一個文件夾中有20個相同類型的文件,字符串與相應的值。 有沒有辦法創建一個可以這種方式打開所有文件的函數
file1 = [line.strip() for line in open("/Python34/elez/file1.txt", "r")]在文件夾中讀取同一個文件的文件

我希望我解釋得很好。 謝謝!

+0

你爲什麼想共同打開20個文件? – 2014-12-18 23:59:56

+0

我需要閱讀每個文件,並在新文件中寫一個摘要 – Gulliver 2014-12-19 00:49:56

回答

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

def contents(filepath): 
    with open(filepath) as f: 
     return f.read() 

directory = '/Python34/elez' 

all_file_contents = [contents(join(directory, filename)) 
        for filename in listdir(directory) 
        if isfile(join(directory, filename)] 
+0

哇這是一個很酷的方式! – biobirdman 2014-12-18 23:59:03

+0

我認爲itertools.chain或生成器會更好 – 2014-12-19 00:09:40

+0

我總是得到這個錯誤 'PermissionError:[Errno 13] Permission denied:'/ Python34/elez'' – Gulliver 2014-12-19 00:33:53

0

喜格列佛,這是我怎麼會做它:

import os 

all_files = [] ## create a list to keep all the lines for all files 


for file in os.listdir('./'): ## use list dir to list all files in the dir 
    with open(file, 'r') as f: ## use with to open file 
     fields = [line.strip() for line in f] ## list comprehension to finish reading the field 
     all_fields.extend(fields) ## store in big list 

更多有關使用with語句來打開和讀取文件,請參考此答案Correct way to write to files?

相關問題