0

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) 
lena
  • 730
  • 2
  • 11
  • 23

1 Answers1

0

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)
itroulli
  • 2,044
  • 1
  • 10
  • 21
  • What do you mean in this key = file.split(".")[0]? and how can get just the value in this dictionary ? – lena Jun 27 '21 at 17:43
  • @kayla The variable `file` contains the string `"onefile.txt"`, so by splitting it on the "." you get the list `["onefile","txt"]` for which you keep the first element ([0]) to use it as key. If you just need the values of the dictionary you can use `files_dict.values()` which returns an iterable. If needed you can convert it to a list explicitly with `list(files_dict.values())`. If you found my answer helpful please accept and upvote it as suggested by the [community guidelines](https://stackoverflow.com/help/someone-answers) – itroulli Jun 27 '21 at 18:10
  • Ok, thank you so much, can you see my code? I'm trying to use list, for me dealing with list values is much easier – lena Jun 27 '21 at 18:17
  • @kayla For your update2, since it seems not related to the first code snippet, if you are using `readlines()` you can replace it with `read().splitlines()`: https://stackoverflow.com/questions/12330522/how-to-read-a-file-without-newlines – itroulli Jun 28 '21 at 07:10