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

标签 python python-2.7

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

#-------------------- 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/

相关文章:

python - 如何查找在线音频文件的持续时间而无需使用python下载?

Python - 使用列表创建字典

python - Scrapy不处理Xpath和CSS选择器中的TBODY

python - 如何在多索引 Pandas 数据框中选择大于某个值的单元格?

python - 使用具有特定值计数的 GroupBy 过滤 Pandas DataFrame

Python 脚本在继续之前等待外部命令完成

python - 如何访问字典中的列表值

python - 计算其他列上给定条件的列类别的唯一值

python-2.7 - 使用 Beautifulsoup 4 进行网页抓取

python-2.7 - 通过网络摄像头检测