【问题标题】:Python writing to file using stdout and fileinputPython使用标准输出和文件输入写入文件
【发布时间】:2012-06-04 20:05:49
【问题描述】:

我有以下代码,它通过进行正则表达式替换来修改文件 test.tex 的每一行。

import re
import fileinput

regex=re.compile(r'^([^&]*)(&)([^&]*)(&)([^&]*)')

for line in fileinput.input('test.tex',inplace=1):
    print regex.sub(r'\3\2\1\4\5',line),

唯一的问题是我只想将替换应用于文件中的某些行,并且无法定义模式来选择正确的行。所以,我想显示每一行并在命令行提示用户,询问是否在当前行进行替换。如果用户输入“y”,则进行替换。如果用户不输入任何内容,则进行替换。

当然,问题在于通过使用代码inplace=1,我有效地将标准输出重定向到打开的文件。因此,无法将输出(例如询问是否进行替换)显示到未发送到文件的命令行。

有什么想法吗?

【问题讨论】:

  • fileinput 不是这项工作的正确工具。只需使用标准的读-修改-写模式
  • @EliBendersky 你能给我举个例子吗?抱歉,我是 Python 新手。
  • 想法?是的。不要就地使用文件输入。对文件执行常规 open(),获取用户输入,写入临时文件,完成后移动临时文件以替换原始文件。

标签: python file-io


【解决方案1】:

文件输入模块实际上是用于处理多个输入文件。 您可以改用常规的 open() 函数。

这样的事情应该可以工作。

通过读取文件然后用 seek() 重置指针,我们可以覆盖文件而不是追加到末尾,从而就地编辑文件

import re

regex = re.compile(r'^([^&]*)(&)([^&]*)(&)([^&]*)')

with open('test.tex', 'r+') as f:
    old = f.readlines() # Pull the file contents to a list
    f.seek(0) # Jump to start, so we overwrite instead of appending
    for line in old:
        s = raw_input(line)
        if s == 'y':
            f.write(regex.sub(r'\3\2\1\4\5',line))
        else:
            f.write(line)

http://docs.python.org/tutorial/inputoutput.html

【讨论】:

  • 当然,如果您的文件太大而无法加载到内存中,那么您可以一次读取一行,然后写入临时文件。
【解决方案2】:

根据每个人提供的帮助,我最终得到了以下结果:

#!/usr/bin/python

import re
import sys
import os

# regular expression
regex = re.compile(r'^([^&]*)(&)([^&]*)(&)([^&]*)')

# name of input and output files
if len(sys.argv)==1:
    print 'No file specified. Exiting.'
    sys.exit()
ifilename = sys.argv[1]
ofilename = ifilename+'.MODIFIED'

# read input file
ifile = open(ifilename)
lines = ifile.readlines()

ofile = open(ofilename,'w')

# prompt to make substitutions wherever a regex match occurs
for line in lines:
    match = regex.search(line)    
    if match is not None:
        print ''
        print '***CANDIDATE FOR SUBSTITUTION***'
        print '--:  '+line,
        print '++:  '+regex.sub(r'\3\2\1\4\5',line),
        print '********************************'
        input = raw_input('Make subsitution (enter y for yes)? ')
        if input == 'y':
            ofile.write(regex.sub(r'\3\2\1\4\5',line))
        else:
            ofile.write(line)
    else:
        ofile.write(line)

# replace original file with modified file
os.remove(ifilename)
os.rename(ofilename, ifilename)

非常感谢!

【讨论】:

    猜你喜欢
    • 2011-04-09
    • 2015-12-27
    • 2018-12-07
    • 1970-01-01
    • 2012-06-01
    • 2013-03-18
    • 1970-01-01
    • 1970-01-01
    • 2012-11-05
    相关资源
    最近更新 更多