Remove lines from files
I have a lot of files which have comments beginning with ! and I need to remove all of those, then replace the #Mhz with # Mhz on the next line and keep the file name same. What is an efficient way of doin开发者_JS百科g this? I can read the file and write to a new file in a different directory and manually delete them later i guess but is there a better way?
Here's a stupidly simple way:
for line in in_file:
if line[0] == '!':
continue
if line.startswith('#Mhz'):
line = '# MHz' + line[4:] # Assuming it's megahertz, it's spelled MHz.
out_file.write(line)
You can read the whole input file and split it into lines then open the file for writing if you want to do it in place.
The fileimput
module is a good choice when you want to filter one (or more) files in-place:
import fileinput
import sys
files_ = fileinput.input(['somefile.ext','anotherfile'], inplace=1)
for line in files_:
if line.startswith('#Mhz'):
sys.stdout.write('# Mhz' + line[4:])
elif line[0] != '!':
sys.stdout.write(line)
files_.close() # cancel stdin & stdout redirection
The first argument to fileinput.input()
can also be a single filename instead of a sequence of them or, if left out, they're automatically taken from successive sys.argv[1:]
arguments, or sys.stdin
if there aren't any -- allowing it to easily handle multiple file seamlessly as written. It can also automatically make backup files and has numerous other useful features, all of which are described in detail in the documentation.
In Python 3.2+ it also can be used in conjunction with a Python with statement which would allow the code above to simplified slightly.
You didn't say anything in the question about why/if it needed to be in python.
If you're only doing this to one or a few files, one very simple way to do this would be to open a file in vim and type
:%s/^!.*\n#Mhz/# Mhz/
and possibly
:%s/^!.*\n//
to get lines to remove that aren't followed by #Mhz
, then save the file and quit with
:wq
With mode 'r+'
, no need of open in 'r' - read - shut - reopen in 'w' - write -shut
, all can be done in the same opening of the same file
From this sentence :
then replace the #Mhz with # Mhz on the next line
I understood that '#Mhz' must be replaced with '# Mhz' only if '#Mhz' is present in a line that follows a line beginning with '!'
If so, the following code does the job for files that are not too big (so that they can easily be loaded in the RAM)
import re
regx = re.compile('^!.*\r?\n((?!!)(.*?)(#Mhz)(.*\r?\n))?',re.MULTILINE)
def repl(mat):
return (mat.group(2)+'# Mhz'+mat.group(4) if mat.group(2)
else mat.group(1))
with open(filename,'r+') as f:
content = f.read()
f.seek(0,0)
f.write(regx.sub(repl,content))
f.truncate()
For enomrous files, another algorithm must be employed.
精彩评论