我有一个名为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'))但是它不起作用。
发布于 2020-11-12 17:20:04
首先,我不知道您实际上是从哪里读取文件的。在正确格式化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。
发布于 2020-11-12 17:15:44
见下文
with open('path_text.txt') as f:
data = [l.strip() for l in f.readlines()]https://stackoverflow.com/questions/64800939
复制相似问题