write specific file name in specific list in python

Viewed 107

I have folder contain multiple .txt files ,the names of files(one.txt,two.txt,three.txt,...) I need to read the one.txt and then write the content of this file in list has name onefile[], then read two.txt and write the content in list twofile[] and so on. how can do this? Update! Iam try this code, now how can print the values in each list ?

 def writeinlist(file_path,i):
    
    multilist = {}    
    output = open(file_path,'r')
    globals()['List%s' % i] = output
    print('List%s' % i)

input_path = Path(Path.home(), "Desktop", "NN")
index=1
for root, dirs, files in os.walk(input_path):
    for file in files:
        file_path = Path(root, file)
        writeinlist(file_path,index)
        index+=1

Update2: how can delete \n from values?

value_list1 = files_dict['file1']
print('Values of file1 are:')
print(value_list1) 
1 Answers

I used the following to create a dictionary with dynamic keys (with the names of the files) and the respective values being a list with elements the lines of the file.

First, contents of onefile.txt:

First file first line
First file second line
First file third line

Contents of twofile.txt:

Second file first line
Second file second line

My code:

import os
import pprint

files_dict = {}
for file in os.listdir("/path/to/folder"):
    if file.endswith(".txt"):
        key = file.split(".")[0]
        full_filename = os.path.join("/path/to/folder", file)
        with open(full_filename, "r") as f:
            files_dict[key] = f.readlines()

pprint.pprint(files_dict)

Output:

{'onefile': ['First file first line\n',
             'First file second line\n',
             'First file third line'],
 'twofile': ['Second file first line\n', 'Second file second line']}

Another way to do this that's a bit more Pythonic:

import os
import pprint

files_dict = {}
for file in [
    f
    for f in os.listdir("/Users/itroulli/Downloads/data_eng_challenge3/files")
    if f.endswith(".txt")
]:
    with open(os.path.join("/path/to/folder", file), "r") as fo:
        files_dict[file.split(".")[0]] = fo.readlines()

pprint.pprint(files_dict)
Related