0

I am working with this list of files in a local directory:

docs = ['5d7d3c905deeb7978034cb40.txt','5d7d3c905deeb7978034cb40.txt','5d7d26ae5deeb7978034cab3.txt',
        '5d7d268e5deeb7978034cab2.txt','5dac3ad15deeb749fcbbfeab.txt']

If I do this:

for doc in docs:

   for txt in open(doc):

I manage to open and read the texts all together. But I want to get each one of them into a distinct variable.

My best solution, for now, is this one:

abstracts = []

for i in range(len(docs)):

   for doc in docs:

      for txt in open(doc):

          txs = [txt] #each text 

          if txs not in abstracts:
             abstracts.append(txs)

I can reach the txs I want by the use of indexes, but I am sure there must be a better way to do this.

powerPixie
  • 718
  • 9
  • 20
  • 1
    Use a dict with the file names as keys? – snakecharmerb Oct 27 '19 at 16:31
  • Possible duplicate of [How do I create a variable number of variables?](https://stackoverflow.com/questions/1373164/how-do-i-create-a-variable-number-of-variables) – snakecharmerb Oct 27 '19 at 18:56
  • @snakecharmerb. It's not as simple as a matter of creating a number of variables, it goes with a specfific task. In this case openning several files in a directory at the same time and being able to make them differ in some way (variable names) – powerPixie Oct 28 '19 at 06:48

3 Answers3

1

Instead use a dict in python.

import os

content_dict = {}

for f_name in os.listdir("."):
    content_dict[f_name.split(".")[0]] = open(f_name).read()

print(content_dict)
bigbounty
  • 16,526
  • 5
  • 37
  • 65
  • I've got this error, trying the code: PermissionError: [Errno 13] Permission denied: '.git' – powerPixie Oct 27 '19 at 16:54
  • Either remove the `.git` repo by doing `rm -rf .git` or follow this - https://stackoverflow.com/questions/36434764/permissionerror-errno-13-permission-denied Or run the script as admin – bigbounty Oct 27 '19 at 16:57
  • He already has the files names.. he didn't ask for a solution of getting a dict of files from a directory.. – kaki gadol Oct 27 '19 at 17:15
  • I suggested him a better way to the same job @kakigadol – bigbounty Oct 27 '19 at 17:31
  • You suggested him a way for a similar but different job.. If we didn't post our answers in about the same time I would have just edit your answer but NVM.. btw I would suggest `pathlib.Path.iterdir()` instead of `os.listdir()` – kaki gadol Oct 27 '19 at 17:56
1

I would use a dictionary which the keys are the files' names and and values are the files' content

files = {}
for doc in docs:
    with open(doc, 'r') as f:
        files[doc] = f.read()
kaki gadol
  • 1,116
  • 1
  • 14
  • 34
0

globals()["name_of_your_variable"] = my_variable will assign a variable based on the string you give it. It should work if you str.split(doc, ".")[0] it first to remove the period.

Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143