gpt4 book ai didi

python - 如何查找并替换txt文件中的属性?

转载 作者:太空宇宙 更新时间:2023-11-03 15:13:09 24 4
gpt4 key购买 nike

我有一个文本文件,其内容如下:

#-------------------- INPUT --------------------
# file name- This is input file name
-input_file
2
/home/useser/file_in1.txt
/home/useser/file_in2.txt
# Output file- this is output file
-output_file
2
/home/useser/file_out1.txt
/home/useser/file_out2.txt

现在,我想用 /home/useser/file_in3.txt/home/useser/替换 /home/useser/file_in1.txt file_in2.txt 通过 /home/users/file_in4.txt 在字段 -input_file 中。相同的过程必须在 -output_file 字段中发生。我正在使用 python 2.7,这就是我尝试过的。但我无法达到预期的结果

#-------------------- INPUT --------------------
# file name- This is input file name
-input_file
2
/home/useser/file_in3.txt
/home/useser/file_in4.txt
# Output file- this is output file
-output_file
2
/home/useser/file_out3.txt
/home/useser/file_out4.txt

我的Python代码是

if __name__ == "__main__":
input_file_3='/home/useser/file_in3.txt'
input_file_4 = '/home/useser/file_in4.txt'
out_file_3='/home/useser/file_out3.txt'
out_file_4 = '/home/useser/file_out4.txt'
f = open('input.txt', 'r')
for line in f:
if '-input_file' in line:
print line

我该怎么办?谢谢

最佳答案

使用str.startwith()str.replace()函数的解决方案:

with open('input.txt', 'r+') as f:  # open file in read/write mode
lines = iter(f.read().splitlines()) # cobverting list to iterator
f.seek(0) # reseting file pointer
for l in lines:
if l.startswith('-input_file'):
num = next(lines)
in1 = next(lines).replace('file_in1.txt', 'file_in3.txt')
in2 = next(lines).replace('file_in2.txt', 'file_in4.txt')
f.write('\n'.join([l, num, in1, in2]) + '\n')
elif l.startswith('-output_file'):
num = next(lines)
out1 = next(lines).replace('file_out1.txt', 'file_out3.txt')
out2 = next(lines).replace('file_out2.txt', 'file_out4.txt')
f.write('\n'.join([l, num, out1, out2]) + '\n')
else:
f.write(l + '\n')

f.truncate()

新的input.txt内容:

#-------------------- INPUT --------------------
# file name- This is input file name
-input_file
2
/home/useser/file_in3.txt
/home/useser/file_in4.txt
# Output file- this is output file
-output_file
2
/home/useser/file_out3.txt
/home/useser/file_out4.txt

关于python - 如何查找并替换txt文件中的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44083800/

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