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

问题描述 投票:1回答:1

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

这样的线条看起来像这样

文件= “形象。&!145.jpg”

我现在坚持到我要么:

  • 删除整个文件中点之间的文本(而不仅仅是以'file ='开头的行)
  • 删除仅以'file ='开头的行之间的点之间的文本,但我最终只在新文档中保存该单行。

这是我到目前为止的代码:

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))

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

有任何想法吗?提前致谢!

python string find save edit
1个回答
1
投票

试试吧。我看到的错误是只编辑条件时进入的那部分。您正在编辑所有文件行。

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))
© www.soinside.com 2019 - 2024. All rights reserved.