在文件夹中读取相同类型的文件

时间:2014-12-18 23:50:57

标签: python file function directory

我需要一些帮助才能完成我的计划。 我在一个文件夹中有20个相同类型的文件,带有相应值的字符串。 有没有办法创建一个以这种方式打开所有文件的功能
file1 = [line.strip() for line in open("/Python34/elez/file1.txt", "r")]

我希望我解释得很清楚。 谢谢!

2 个答案:

答案 0 :(得分: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)]

答案 1 :(得分:0)

嗨Gulliver这是我将如何做到的:

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?