将python中由换行符分隔的字符串文件解析为json数组

2024-04-28 22:59:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为path_text.txt的文件,其内容是由换行符分隔的两个字符串:

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

我想要一个json数组对象,如下所示:

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

我试过这样的方法:

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

但它不起作用


Tags: 文件pathtexttxtmedmyfilesmallgp
2条回答

见下文

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

我看不出你一开始是在哪里读文件的。你必须先阅读你的path_text.txt,然后才能正确格式化,对吗

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

这将在content中为您提供['/gp/oi/eu/gatk/inputs/NA12878_24RG_med.hg38.bam', '/gp/oi/eu/gatk/inputs/NA12878_24RG_small.hg38.bam']

现在,如果要将此数据写入格式为["/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)

现在path_json.json文件看起来像-

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

如果您想从文件中加载json,这是有效的json

相关问题 更多 >