提问人:Fakir 提问时间:3/12/2023 最后编辑:mkrieger1Fakir 更新时间:3/12/2023 访问量:61
替换文件中的单词以添加另一个文件内容 [重复]
Replacing a word in a file to add another file content [duplicate]
问:
输入文件 (csv)。
NAME,TYPE,ACCESS_TOKEN
dev765,datatype,Token765
dev879,datatype,Token879
附加文件:
{
"file": "string",
"mapping": {
"columns": [
{
"type": "NAME"
},
{
"type": "TYPE"
},
{
"type": "ACCESS_TOKEN"
}
],
"delimiter": ",",
"header": true,
"update": true
}
}
目标是将“附加文件”中的“字符串”替换为“输入文件”的内容,并带有换行符。因此,生成的“附加文件”文件应如下所示:
{
"file": "NAME,TYPE,ACCESS_TOKEN\n dev765,datatype,Token765\n dev879,datatype,Token879",
"mapping": {
"columns": [
{
"type": "NAME"
},
{
"type": "TYPE"
},
{
"type": "ACCESS_TOKEN"
}
],
"delimiter": ",",
"header": true,
"update": true
}
}
我实际需要的是“Append.txt”文件的第一行:
{
"file": "_the_content_of_the_input_file_with_\n_break",
REST OF THE FILE AS IT IS
....
....
}
如果文件是纯文本,我可以在开头或结尾附加整个文件。或者用另一个词替换一个词。但只是不知道如何处理上述格式以及如何用整个文件替换单词。
答:
1赞
Jamiu S.
3/12/2023
#1
试试这种方法。
with (open("input.csv", "r") as infile,
open("append_file.json", "r") as append_file,
open("output_file.json", "w") as outfile):
infile_content = infile.read().strip()
infile_content = infile_content.replace("\n", "\\n ")
# You can also use the join() approach
# infile_content = "\n ".join(infile.readlines())
append_file_content = json.load(append_file)
append_file_content["file"] = infile_content
json.dump(append_file_content, outfile, indent=2)
测试代码:
import json
input_file_content = """NAME,TYPE,ACCESS_TOKEN
dev765,datatype,Token765
dev879,datatype,Token879
"""
input_file_content = "\n ".join(input_file_content.splitlines())
append_file_content = {
"file": "string",
"mapping": {
"columns": [
{
"type": "NAME"
},
{
"type": "TYPE"
},
{
"type": "ACCESS_TOKEN"
}
],
"delimiter": ",",
"header": True,
"update": True
}
}
append_file_content["file"] = input_file_content
print(json.dumps(append_file_content, indent=2))
{
"file": "NAME,TYPE,ACCESS_TOKEN\n dev765,datatype,Token765\n dev879,datatype,Token879",
"mapping": {
"columns": [
{
"type": "NAME"
},
{
"type": "TYPE"
},
{
"type": "ACCESS_TOKEN"
}
],
"delimiter": ",",
"header": true,
"update": true
}
}
评论
1赞
Fakir
3/12/2023
完善!非常感谢!我也刚刚使用输出进行了测试,它可以将带有测试 API 的测试 JSON 值发送到缩进系统平台并注册这些值。
评论