[英]How to write in a dat file in python
我在一个可以轻松访问的 dat 文件中包含此内容,它不在文件的开头而是在中间。 我只插入我需要修改的文件部分。
{
....,
"Rot": {
"RM": [
",>=,",
",>=,",
",>=,",
",>=,",
",>=,",
",>=,",
",>=,",
",>=,",
",>=,",
",>=,",
",>=,",
",>=,",
",>=,",
",>=,",
",>=,",
",>=,",
",>=,",
",>=,",
",>=,",
",>=,"
]
},
.......
}
而不是带有",>=,",
我希望我可以从python代码中插入一个自定义字符串,例如"M,<=,5",
,因为我必须对许多文件/多次执行此操作。 我可以通过这个脚本读取文件,但我不明白如何在 python 代码中找到我想要更改的行以及如何在其中覆盖我感兴趣的字符串。
prefixed = [filename for filename in os.listdir('.') if filename.startswith("CRY")] #NQ, DIV, ecc..
for i in range(len(prefixed)):
with open(prefixed[i], 'r') as file:
lines = file.readlines()
print(lines)
prefixed = [filename for filename in os.listdir('.') if filename.startswith("CRY")] #NQ, DIV, ecc..
for i in range(len(prefixed)):
# Read lines
file = open(prefixed[i], 'r')
file_content = file.readlines()
file.close()
# Treatment
for pos, line in enumerate(file_content):
if ",>=," in line:
file_content[pos] = line.replace(",>=,", "myCustomString")
# Write lines
file = open(prefixed[i], 'w')
file.writelines(file_content)
file.close()
只修改第一个元素:
prefixed = [filename for filename in os.listdir('.') if filename.startswith("CRY")] #NQ, DIV, ecc..
for i in range(len(prefixed)):
# Read lines
file = open(prefixed[i], 'r')
file_content = file.readlines()
file.close()
# Treatment
for pos, line in enumerate(file_content):
if ",>=," in line:
file_content[pos] = line.replace(",>=,", "myCustomString")
# Add break to quit loop after first replacement
break
# Write lines
file = open(prefixed[i], 'w')
file.writelines(file_content)
file.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.