0

I Selected my needed Data Like This:

import pathlib
from pathlib import Path
import glob, os

folder = Path('D:/xyz/123/Files')

os.chdir(folder)
for file in glob.glob("*.json"):
    JsonFiles = os.path.join(folder, file)
    print (JsonFiles)

As Output I will get all my needed .json Files

D:/xyz/123/Files/Data.json
D:/xyz/123/Files/Stuff.json
D:/xyz/123/Files/Random.json
D:/xyz/123/Files/Banana.json
D:/xyz/123/Files/Apple.json

For my further coding in need a Variable to the diffrens Json Paths. So my Idear was insted of printing them to store them in a List. But thats not working?

ListJson =[JsonFiles]
print (ListJson[1])

I get this Error:

print (ListJson[2])
IndexError: list index out of range

How wold you solve this Problem I just need an possibility to work with the Paths I already sorted.

Nimantha
  • 6,405
  • 6
  • 28
  • 69
zoozle
  • 21
  • 2

2 Answers2

0

Solution 1 with append():

If you change

for file in glob.glob("*.json"):
    JsonFiles = os.path.join(folder, file)
    print (JsonFiles)

to

ListJson = []
for file in glob.glob("*.json"):
    JsonFile = os.path.join(folder, file)
    ListJson.append(JsonFile)

You create an empty list and add during each iteration one file (the result of os.path.join to it.

then you would have what you want

Solution 2 with list comprehensions:

If you want to use list comprehensions ( https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions ) , then following would do:

ListJson = [os.path.join(folder, file) for file in glob.glob("*.json")]

Solution 3: with pathlib, absolute() and glob():

On the other hand you don't even have to chdir() into the given directory and if path objects are good enough in your context you could directly do:

ListJson = list(folder.absolute().glob('*.json'))

or if you really need strings:

ListJson = [str(path) for path in folder.absolute().glob('*.json')]

KlausF
  • 152
  • 8
  • Thank you that workt perfectly! I will read now some more about list comprehensions thank you for your Help and the further Information. – zoozle Mar 17 '21 at 10:46
  • Please don't forget to upvote the answers, that helped you and choose one of the answers as solution. You can of course wait some more time to see whether you get an even better answer and mark that one as 'correct' answer – KlausF Mar 17 '21 at 10:51
0

You can use Python List append() Method

import pathlib
from pathlib import Path
import glob, os

folder = Path('D:/xyz/123/Files')
ListJson=[]
os.chdir(folder)
for file in glob.glob("*.json"):
    JsonFiles = os.path.join(folder, file)
    ListJson.append(JsonFiles)

print(ListJson)
Nimantha
  • 6,405
  • 6
  • 28
  • 69