Python 在文件中查找字符串,编辑行并保存到新文件

Python find string in file, edit line and save to a new file

我正在尝试浏览一个文本文件并找到所有以 'file=' 开头的行。当我找到这些行时,我想删除点之间的所有文本,最后将其另存为一个新文件。

这样的线条看起来像这样

file="image.&!145.jpg"

我目前被困在我所在的地方:

这是我目前的代码:

import os
from os.path import basename
from re import sub


file_in = 'tex_file_01.txt'
file_out = 'tex_file_01_new.txt'


with open(file_in, 'r') as f_in:
    with open(file_out, 'w') as f_out:
        for line in f_in:
            if 'file=' in line:
                print 'found: ' + line

            line_fix = sub('\..*?\.', '.', line)
            print 'fixed: ' + line_fix

            f_out.write(line.replace(line, line_fix))

以上代码删除了整个文件中点之间的文本。

有什么想法吗?提前致谢!

试试这个。我看到的唯一错误是出现在 if 条件中的那部分。您正在编辑文件的所有行。

import os
from os.path import basename
from re import sub


file_in = 'tex_file_01.txt'
file_out = 'tex_file_01_new.txt'


with open(file_in, 'r') as f_in:
    with open(file_out, 'w') as f_out:
        for line in f_in:
            if 'file=' in line:
                print('found: ' + line)
                line_fix = sub('\..*?\.', '.', line)
            else:
                line_fix = line
            print('fixed: ' + line_fix)
            
            f_out.write(line.replace(line, line_fix))