如何使用fileinput编辑多个文件? [英] how can i use fileinput to edit multiple files?

查看:137
本文介绍了如何使用fileinput编辑多个文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在python 2.7中使用os.walk打开多个文件,然后将这些文件的所有感兴趣的行添加到列表中.稍后,我想用fileinput编辑这些行并关闭它.我怎样才能做到这一点?使用以下代码打开文件:

I am using os.walk in python 2.7 to open multiple files, then, add all lines of interest of those files to a list. Later I'd want to edit those lines with fileinput and close it. How can I achieve this? Using the code below is how I'm opening the files:

import os
import fnmatch
import fileinput

lines = []

def openFiles():
    for root, dirs, files in os.walk('/home/test1/'):
        for lists in fnmatch.filter(files, "*.txt"):
            filepath = os.path.join(root, lists)
            print filepath
            with open(filepath, "r") as sources:#opens 8 files and read their lines
                #edit = fileinput.input(filepath, inplace=1)
                for line in sources:
                    if line.startswith('xe') :
                      lines.append(line)

然后,对于以xe开头的每一行,我想在其前面添加#,然后关闭该文件.我想通过其他功能来做到这一点.

Then later, for each lines that start with xe, I'd like to add a # in front of it then close that file. I'd like to do that in a different function.

推荐答案

我最终还是这样做了.但是我在主代码中使用了类,因此将其拆分为2个函数,而不是一个.在我的主代码中,我使用了一个列表来保存所有文件路径,并使用fileinput通过这种方式打开列表中的每个文件路径for line in fileinput.FileInput(pathlist, inplace=1): do something.我非常感谢@direprobs的回答,因为她阐明了我的想法为此.

I ended up doing it this way. But I'm using classes in my main code so It's split into 2 functions instead of one. In my main code, I used a list to hold all the file paths and use fileinput to open each filepaths from the list this way for line in fileinput.FileInput(pathlist, inplace=1): do something. I do thank @direprobs for her answer, as she shed some light on how I'm supposed to do this.

import fnmatch
import fileinput
import os
import sys

def openFiles():
    for dirpath, dirs, files in os.walk('/home/test1/'):
        for filename in fnmatch.filter(files, "*.txt"):
            filepaths = os.path.join(dirpath, filename)
            for line in fileinput.FileInput(filepaths, inplace=1):
                if line.startswith("xe"):
                    add = "# {}".format(line)
                    line = line.replace(line, add)
                sys.stdout.write(line)
                fileinput.close()


openFiles()

这篇关于如何使用fileinput编辑多个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆