gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 09:36:54 29 4
gpt4 key购买 nike

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

/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'))

但是没有效果

最佳答案

我一开始并没有看到您实际从文件中读取的位置。您必须真正阅读您的 path_text.txt 才能正确格式化它吗?

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

这会给你 ['/gp/oi/eu/gatk/inputs/NA12878_24RG_med.hg38.bam', '/gp/oi/eu/gatk/inputs/NA12878_24RG_small.hg38.bam']content 中。

现在,如果您想将此数据写入格式为 ["/gp/oi/eu/gatk/inputs/NA12878_24RG_med.hg38.bam", "/gp/oi/eu/gatk/输入/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

关于python - 将python中由换行符分隔的字符串文件解析为json数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64800939/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com