2

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

moth
  • 1,833
  • 12
  • 29
  • 3
    You say you want to ***read*** the file to JSON, but your code is ***writing*** to the file. Which one are you actually trying to do? If you're trying to read, why not just `file.readlines()`? – Tomerikoo Nov 12 '20 at 09:15
  • 1
    read yes. I'm sorry, I was trying to write comma (,) and double quotes (") into the existing file. thats why i used write – moth Nov 12 '20 at 09:21
  • 1
    Does this answer your question? [How to read a file line-by-line into a list?](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list) followed by [How do I write JSON data to a file?](https://stackoverflow.com/questions/12309269/how-do-i-write-json-data-to-a-file) – Tomerikoo Nov 12 '20 at 09:28

2 Answers2

4

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

Chase
  • 5,315
  • 2
  • 15
  • 41
  • @Tomerikoo true, I have no idea how I managed to forget using `json.dump` in my answer at first while simultaneously mentioning it in a comment – Chase Nov 12 '20 at 10:12
  • @Chase yeah I noticed that in the moment ^_^ All good... now it looks fine :) – Tomerikoo Nov 12 '20 at 10:13
3

see below

with open('path_text.txt') as f:
    data = [l.strip() for l in f.readlines()]
balderman
  • 22,927
  • 7
  • 34
  • 52