0

I'm new to python, and couldn't find a close enough answer to make me figure it out. I'm trying generate a single json file that contains current directory file names that end with a .txt extension as nodes, and the contents of those files as a list inside the file name's node.

for example:

node1.txt contains

foo
bar

and node2.txt contains

test1
test2

the output should look like:

{
  "node1": [
     "foo",
     "bar"
   ],
   "node2": [
     "test1",
     "test2"
   ]
}


4
  • 2
    You should provide your best attempt(s), so we can see where you are actually stuck. Commented Aug 1, 2021 at 12:44
  • As a starting point I suggest you take a look at the glob module docs.python.org/3/library/glob.html Commented Aug 1, 2021 at 12:47
  • @AndyKnight. I suggest instead the OP takes a look to Welcome to Stack Overflow Commented Aug 1, 2021 at 12:51
  • you need to learn 1) how to read a file. 2) how to generate json. 3) how to write to a file. These are what you should be asking yourself. Rather than asking for an end to end solution. Commented Aug 1, 2021 at 12:52

1 Answer 1

3

Use pathlib and json modules and a simple loop...

import pathlib
import json

data = {}
for node in pathlib.Path('.').glob('node*.txt'):
    with open(node, 'r') as fp:
        data[node.stem] = [line.strip() for line in fp.readlines()]

print(json.dumps(data, indent=4))

Output:

{
    "node1": [
        "foo",
        "bar"
    ],
    "node2": [
        "test1",
        "test2"
    ]
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.