如何通过python编辑文件夹中所有文本文件的特定行?

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

下面是我的代码,关于如何编辑文本文件。

由于python不能只编辑一行并同时保存它,

我先将文本文件的内容保存到列表中,然后将其写出来。

例如,如果在同一文件夹中有两个名为sample1.txt和sample2.txt的文本文件。

Sample1.txt 一个苹果。

第二行。

第三行。

Sample2.txt 第一行。

一天一个苹果。

第三行。

执行python

import glob
import os

#search all text files which are in the same folder with python script
path = os.path.dirname(os.path.abspath(__file__))
txtlist = glob.glob(path + '\*.txt')

for file in txtlist:
    fp1 = open(file, 'r+')
    strings = [] #create a list to store the content
    for line in fp1:
        if 'apple' in line:
            strings.append('banana\n') #change the content and store into list
        else:
            strings.append(line) #store the contents did not be changed
    fp2 = open (file, 'w+') # rewrite the original text files
    for line in strings:
        fp2.write(line)
    fp1.close()
    fp2.close()

Sample1.txt 香蕉

第二行。

第三行。

Sample2.txt 第一行。

香蕉

第三行。


这就是我编辑文本文件的特定行的方式。

我的问题是:有什么方法可以做同样的事情吗?

像使用其他函数或使用其他数据类型而不是列表。

谢谢大家。

python text-files edit
4个回答
1
投票

简化它:

with open(fname) as f:
    content = f.readlines()
    content = ['banana' if line.find('apple') != -1 else line for line in content]

然后将content的值写回文件。


0
投票

您可以将其读入内存,替换并使用相同的文件写入,而不是将所有行放在列表中并进行编写。

def replace_word(filename):
    with open(filename, 'r') as file:
       data = file.read()

    data = data.replace('word1', 'word2')

    with open(filename, 'w') as file:
        file.write(data)

然后,您可以遍历所有文件并应用此功能


0
投票

内置的fileinput模块使这很简单:

import fileinput
import glob

with fileinput.input(files=glob.glob('*.txt'), inplace=True) as files:
    for line in files:
        if 'apple' in line:
            print('banana')
        else:
            print(line, end='')

fileinputprint重定向到活动文件。


0
投票
import glob
import os


def replace_line(file_path, replace_table: dict) -> None:
    list_lines = []
    need_rewrite = False
    with open(file_path, 'r') as f:
        for line in f:
            flag_rewrite = False
            for key, new_val in replace_table.items():
                if key in line:
                    list_lines.append(new_val+'\n')
                    flag_rewrite = True
                    need_rewrite = True
                    break  # only replace first find the words.

            if not flag_rewrite:
                list_lines.append(line)

    if not need_rewrite:
        return

    with open(file_path, 'w') as f:
        [f.write(line) for line in list_lines]


if __name__ == '__main__':
    work_dir = os.path.dirname(os.path.abspath(__file__))
    txt_list = glob.glob(work_dir + '/*.txt')
    replace_dict = dict(apple='banana', orange='grape')

    for txt_path in txt_list:
        replace_line(txt_path, replace_dict)
© www.soinside.com 2019 - 2024. All rights reserved.