这是输入列表(在file_id.txt中):
file-F0Y6GbQ09k704jfGBQX0pgF8
file-FfYqQv00ypGfqQKkF96zX3yV
file-FfYqPf80ypGj712qFBggV2BV
file-FfQpFYQ0ypGqfjkJ8z90Ygzv
file-FfQpFYQ0ypGpQ4K7GGj40VVZ
file-FfQpFYQ0ypGxV3xG7BZQxz3y
file-FfQpFYQ0ypGZ3ZVk7745ZGFf
file-Ff0Qk100ypGYV26V52JZkJ0q
file-FfK1pZ80ypGjgyF73b3fFjgG
这是所需的输出(output.json):
{
"stage-xxx.input_files": [
{"$dnanexus_link": "file-F0Y6GbQ09k704jfGBQX0pgF8"},
{"$dnanexus_link": "file-FfYqQv00ypGfqQKkF96zX3yV"},
{"$dnanexus_link": "file-FfYqPf80ypGj712qFBggV2BV"},
{"$dnanexus_link": "file-FfQpFYQ0ypGqfjkJ8z90Ygzv"},
{"$dnanexus_link": "file-FfQpFYQ0ypGpQ4K7GGj40VVZ"},
{"$dnanexus_link": "file-FfQpFYQ0ypGxV3xG7BZQxz3y"},
{"$dnanexus_link": "file-FfQpFYQ0ypGZ3ZVk7745ZGFf"},
{"$dnanexus_link": "file-Ff0Qk100ypGYV26V52JZkJ0q"},
{"$dnanexus_link": "file-FfK1pZ80ypGjgyF73b3fFjgG"}
]
}
这是我当前的代码:
#!/usr/bin/python3 env
fname = input("Enter file name of the list: ")
if len(fname) < 1 : fname = "file_id.txt"
stage_name = input("Enter stage name for the input: ")
if len(stage_name) < 1 : stage_name = "stage-xxx"
input_var = input("Enter input variable name: ")
if len(input_var) < 1 : input_var = "input_files"
fh = open(fname)
out_file = open('output.json', 'w')
out_file.write('{\n "' + f'{stage_name}' + "." + f'{input_var}' + '": [' + "\n")
for line in fh:
fileid = line.rstrip()
out_file.write(" {" + "\"$dnanexus_link\": " + f'"{fileid}"' + "},\n")
out_file.write(' ]\n}\n')
out_file.close()
print("output.json created!")
我是python的新手,不确定在输出json中最后一个文件的末尾如何删除逗号。而且我想知道是否有一种方法可以使用json模块将文件列表转储为json格式,而无需使用静态文本编码。.
答案 0 :(得分:1)
此代码读取list
个文件中dict
个的文件。
然后我将此list
包装在最后的dict
中,并使用json.dumps()获得一个字符串:
import json
with open('file_id.txt') as f:
txt = [{'$dnanexus_link': line.strip()} for line in f]
#print(txt)
d = {'stage-xxx.input_files': txt}
print(json.dumps(d))
输出为您的output.json
,但仅输出一行。