0

I need a little help to finish my program. I have in a folder 20 files of the same typology, strings with corresponding values. Is there a way to create a function that opens all the files in this way
file1 = [line.strip() for line in open("/Python34/elez/file1.txt", "r")]?

I hope I explained it well. Thanks!

Gulliver
  • 31
  • 5

2 Answers2

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)]
Peter Wood
  • 23,859
  • 5
  • 60
  • 99
0

Hi Gulliver this is how i will do it:

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 

For more information about using the with statement to open and read files, please refer to this answer Correct way to write to files?

Community
  • 1
  • 1
biobirdman
  • 4,060
  • 1
  • 17
  • 15