Parse a file of strings in python separated by newline into a json array

Viewed 104

I have a file called path_text.txt its contents are the 2 strings separated by newline:

/gp/oi/eu/gatk/inputs/NA12878_24RG_med.hg38.bam 
/gp/oi/eu/gatk/inputs/NA12878_24RG_small.hg38.bam

I would like to have a json array object like this:

["/gp/oi/eu/gatk/inputs/NA12878_24RG_med.hg38.bam","/gp/oi/eu/gatk/inputs/NA12878_24RG_small.hg38.bam"]

I have tried something like this:

with open('path_text.txt','w',encoding='utf-8') as myfile:
    myfile.write(','.join('\n'))

But it does not work

2 Answers

I don't see where you're actually reading from the file in the first place. You have to actually read your path_text.txt before you can format it correctly right?

with open('path_text.txt','r',encoding='utf-8') as myfile:
    content = myfiel.read().splitlines()

Which will give you ['/gp/oi/eu/gatk/inputs/NA12878_24RG_med.hg38.bam', '/gp/oi/eu/gatk/inputs/NA12878_24RG_small.hg38.bam'] in content.

Now if you want to write this data to a file in the format ["/gp/oi/eu/gatk/inputs/NA12878_24RG_med.hg38.bam", "/gp/oi/eu/gatk/inputs/NA12878_24RG_small.hg38.bam"]-

import json

with open('path_json.json', 'w') as f:
    json.dump(content, f)

Now the path_json.json file looks like-

["/gp/oi/eu/gatk/inputs/NA12878_24RG_med.hg38.bam", "/gp/oi/eu/gatk/inputs/NA12878_24RG_small.hg38.bam"]

which is valid json in case you want to load a json from a file

see below

with open('path_text.txt') as f:
    data = [l.strip() for l in f.readlines()]
Related