Writing Python to a file using stdout and fileinput

I have the following code that modifies every line of the test.tex file by replacing the regular expression.

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

The only problem is that I want the substitution applied to certain lines in the file, and there is no way to define a pattern to select the correct lines. So, I want to display each line and ask the user on the command line, asking whether to make a replacement in the current line. If the user enters "y", a replacement is performed. If the user simply does not enter anything, the substitution is not performed.

The problem, of course, is that with the inplace=1 code, I effectively redirected stdout to an open file. Thus, there is no way to show the output (for example, the question of whether to make a replacement) on the command line that is not sent to the file.

Any ideas?

+6
source share
2 answers

The file input module is really designed to work with multiple input files. Instead, you can use the regular open () function.

Something like this should work.

After reading the file, and then resetting the pointer using the search function (), we can override the file instead of adding it to the end and thus edit the file in place

 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

+3
source

Based on the help that everyone provided, here is what I ended up with:

 #!/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) 

Thanks a lot!

0
source

Source: https://habr.com/ru/post/917023/


All Articles