Edit File by line
/home/barbar84/www/wp-conte.../plugins/sujqvwi/AnonR/anonr.TX.../usr/lib64/python3....
File: fileinput.py
"""Helper class to quickly write a loop over all standard input files.
[0] Fix | Delete
[1] Fix | Delete
Typical use is:
[2] Fix | Delete
[3] Fix | Delete
import fileinput
[4] Fix | Delete
for line in fileinput.input():
[5] Fix | Delete
process(line)
[6] Fix | Delete
[7] Fix | Delete
This iterates over the lines of all files listed in sys.argv[1:],
[8] Fix | Delete
defaulting to sys.stdin if the list is empty. If a filename is '-' it
[9] Fix | Delete
is also replaced by sys.stdin and the optional arguments mode and
[10] Fix | Delete
openhook are ignored. To specify an alternative list of filenames,
[11] Fix | Delete
pass it as the argument to input(). A single file name is also allowed.
[12] Fix | Delete
[13] Fix | Delete
Functions filename(), lineno() return the filename and cumulative line
[14] Fix | Delete
number of the line that has just been read; filelineno() returns its
[15] Fix | Delete
line number in the current file; isfirstline() returns true iff the
[16] Fix | Delete
line just read is the first line of its file; isstdin() returns true
[17] Fix | Delete
iff the line was read from sys.stdin. Function nextfile() closes the
[18] Fix | Delete
current file so that the next iteration will read the first line from
[19] Fix | Delete
the next file (if any); lines not read from the file will not count
[20] Fix | Delete
towards the cumulative line count; the filename is not changed until
[21] Fix | Delete
after the first line of the next file has been read. Function close()
[22] Fix | Delete
closes the sequence.
[23] Fix | Delete
[24] Fix | Delete
Before any lines have been read, filename() returns None and both line
[25] Fix | Delete
numbers are zero; nextfile() has no effect. After all lines have been
[26] Fix | Delete
read, filename() and the line number functions return the values
[27] Fix | Delete
pertaining to the last line read; nextfile() has no effect.
[28] Fix | Delete
[29] Fix | Delete
All files are opened in text mode by default, you can override this by
[30] Fix | Delete
setting the mode parameter to input() or FileInput.__init__().
[31] Fix | Delete
If an I/O error occurs during opening or reading a file, the OSError
[32] Fix | Delete
exception is raised.
[33] Fix | Delete
[34] Fix | Delete
If sys.stdin is used more than once, the second and further use will
[35] Fix | Delete
return no lines, except perhaps for interactive use, or if it has been
[36] Fix | Delete
explicitly reset (e.g. using sys.stdin.seek(0)).
[37] Fix | Delete
[38] Fix | Delete
Empty files are opened and immediately closed; the only time their
[39] Fix | Delete
presence in the list of filenames is noticeable at all is when the
[40] Fix | Delete
last file opened is empty.
[41] Fix | Delete
[42] Fix | Delete
It is possible that the last line of a file doesn't end in a newline
[43] Fix | Delete
character; otherwise lines are returned including the trailing
[44] Fix | Delete
newline.
[45] Fix | Delete
[46] Fix | Delete
Class FileInput is the implementation; its methods filename(),
[47] Fix | Delete
lineno(), fileline(), isfirstline(), isstdin(), nextfile() and close()
[48] Fix | Delete
correspond to the functions in the module. In addition it has a
[49] Fix | Delete
readline() method which returns the next input line, and a
[50] Fix | Delete
__getitem__() method which implements the sequence behavior. The
[51] Fix | Delete
sequence must be accessed in strictly sequential order; sequence
[52] Fix | Delete
access and readline() cannot be mixed.
[53] Fix | Delete
[54] Fix | Delete
Optional in-place filtering: if the keyword argument inplace=1 is
[55] Fix | Delete
passed to input() or to the FileInput constructor, the file is moved
[56] Fix | Delete
to a backup file and standard output is directed to the input file.
[57] Fix | Delete
This makes it possible to write a filter that rewrites its input file
[58] Fix | Delete
in place. If the keyword argument backup=".<some extension>" is also
[59] Fix | Delete
given, it specifies the extension for the backup file, and the backup
[60] Fix | Delete
file remains around; by default, the extension is ".bak" and it is
[61] Fix | Delete
deleted when the output file is closed. In-place filtering is
[62] Fix | Delete
disabled when standard input is read. XXX The current implementation
[63] Fix | Delete
does not work for MS-DOS 8+3 filesystems.
[64] Fix | Delete
[65] Fix | Delete
XXX Possible additions:
[66] Fix | Delete
[67] Fix | Delete
- optional getopt argument processing
[68] Fix | Delete
- isatty()
[69] Fix | Delete
- read(), read(size), even readlines()
[70] Fix | Delete
[71] Fix | Delete
"""
[72] Fix | Delete
[73] Fix | Delete
import sys, os
[74] Fix | Delete
[75] Fix | Delete
__all__ = ["input", "close", "nextfile", "filename", "lineno", "filelineno",
[76] Fix | Delete
"fileno", "isfirstline", "isstdin", "FileInput", "hook_compressed",
[77] Fix | Delete
"hook_encoded"]
[78] Fix | Delete
[79] Fix | Delete
_state = None
[80] Fix | Delete
[81] Fix | Delete
def input(files=None, inplace=False, backup="", *, mode="r", openhook=None):
[82] Fix | Delete
"""Return an instance of the FileInput class, which can be iterated.
[83] Fix | Delete
[84] Fix | Delete
The parameters are passed to the constructor of the FileInput class.
[85] Fix | Delete
The returned instance, in addition to being an iterator,
[86] Fix | Delete
keeps global state for the functions of this module,.
[87] Fix | Delete
"""
[88] Fix | Delete
global _state
[89] Fix | Delete
if _state and _state._file:
[90] Fix | Delete
raise RuntimeError("input() already active")
[91] Fix | Delete
_state = FileInput(files, inplace, backup, mode=mode, openhook=openhook)
[92] Fix | Delete
return _state
[93] Fix | Delete
[94] Fix | Delete
def close():
[95] Fix | Delete
"""Close the sequence."""
[96] Fix | Delete
global _state
[97] Fix | Delete
state = _state
[98] Fix | Delete
_state = None
[99] Fix | Delete
if state:
[100] Fix | Delete
state.close()
[101] Fix | Delete
[102] Fix | Delete
def nextfile():
[103] Fix | Delete
"""
[104] Fix | Delete
Close the current file so that the next iteration will read the first
[105] Fix | Delete
line from the next file (if any); lines not read from the file will
[106] Fix | Delete
not count towards the cumulative line count. The filename is not
[107] Fix | Delete
changed until after the first line of the next file has been read.
[108] Fix | Delete
Before the first line has been read, this function has no effect;
[109] Fix | Delete
it cannot be used to skip the first file. After the last line of the
[110] Fix | Delete
last file has been read, this function has no effect.
[111] Fix | Delete
"""
[112] Fix | Delete
if not _state:
[113] Fix | Delete
raise RuntimeError("no active input()")
[114] Fix | Delete
return _state.nextfile()
[115] Fix | Delete
[116] Fix | Delete
def filename():
[117] Fix | Delete
"""
[118] Fix | Delete
Return the name of the file currently being read.
[119] Fix | Delete
Before the first line has been read, returns None.
[120] Fix | Delete
"""
[121] Fix | Delete
if not _state:
[122] Fix | Delete
raise RuntimeError("no active input()")
[123] Fix | Delete
return _state.filename()
[124] Fix | Delete
[125] Fix | Delete
def lineno():
[126] Fix | Delete
"""
[127] Fix | Delete
Return the cumulative line number of the line that has just been read.
[128] Fix | Delete
Before the first line has been read, returns 0. After the last line
[129] Fix | Delete
of the last file has been read, returns the line number of that line.
[130] Fix | Delete
"""
[131] Fix | Delete
if not _state:
[132] Fix | Delete
raise RuntimeError("no active input()")
[133] Fix | Delete
return _state.lineno()
[134] Fix | Delete
[135] Fix | Delete
def filelineno():
[136] Fix | Delete
"""
[137] Fix | Delete
Return the line number in the current file. Before the first line
[138] Fix | Delete
has been read, returns 0. After the last line of the last file has
[139] Fix | Delete
been read, returns the line number of that line within the file.
[140] Fix | Delete
"""
[141] Fix | Delete
if not _state:
[142] Fix | Delete
raise RuntimeError("no active input()")
[143] Fix | Delete
return _state.filelineno()
[144] Fix | Delete
[145] Fix | Delete
def fileno():
[146] Fix | Delete
"""
[147] Fix | Delete
Return the file number of the current file. When no file is currently
[148] Fix | Delete
opened, returns -1.
[149] Fix | Delete
"""
[150] Fix | Delete
if not _state:
[151] Fix | Delete
raise RuntimeError("no active input()")
[152] Fix | Delete
return _state.fileno()
[153] Fix | Delete
[154] Fix | Delete
def isfirstline():
[155] Fix | Delete
"""
[156] Fix | Delete
Returns true the line just read is the first line of its file,
[157] Fix | Delete
otherwise returns false.
[158] Fix | Delete
"""
[159] Fix | Delete
if not _state:
[160] Fix | Delete
raise RuntimeError("no active input()")
[161] Fix | Delete
return _state.isfirstline()
[162] Fix | Delete
[163] Fix | Delete
def isstdin():
[164] Fix | Delete
"""
[165] Fix | Delete
Returns true if the last line was read from sys.stdin,
[166] Fix | Delete
otherwise returns false.
[167] Fix | Delete
"""
[168] Fix | Delete
if not _state:
[169] Fix | Delete
raise RuntimeError("no active input()")
[170] Fix | Delete
return _state.isstdin()
[171] Fix | Delete
[172] Fix | Delete
class FileInput:
[173] Fix | Delete
"""FileInput([files[, inplace[, backup]]], *, mode=None, openhook=None)
[174] Fix | Delete
[175] Fix | Delete
Class FileInput is the implementation of the module; its methods
[176] Fix | Delete
filename(), lineno(), fileline(), isfirstline(), isstdin(), fileno(),
[177] Fix | Delete
nextfile() and close() correspond to the functions of the same name
[178] Fix | Delete
in the module.
[179] Fix | Delete
In addition it has a readline() method which returns the next
[180] Fix | Delete
input line, and a __getitem__() method which implements the
[181] Fix | Delete
sequence behavior. The sequence must be accessed in strictly
[182] Fix | Delete
sequential order; random access and readline() cannot be mixed.
[183] Fix | Delete
"""
[184] Fix | Delete
[185] Fix | Delete
def __init__(self, files=None, inplace=False, backup="", *,
[186] Fix | Delete
mode="r", openhook=None):
[187] Fix | Delete
if isinstance(files, str):
[188] Fix | Delete
files = (files,)
[189] Fix | Delete
elif isinstance(files, os.PathLike):
[190] Fix | Delete
files = (os.fspath(files), )
[191] Fix | Delete
else:
[192] Fix | Delete
if files is None:
[193] Fix | Delete
files = sys.argv[1:]
[194] Fix | Delete
if not files:
[195] Fix | Delete
files = ('-',)
[196] Fix | Delete
else:
[197] Fix | Delete
files = tuple(files)
[198] Fix | Delete
self._files = files
[199] Fix | Delete
self._inplace = inplace
[200] Fix | Delete
self._backup = backup
[201] Fix | Delete
self._savestdout = None
[202] Fix | Delete
self._output = None
[203] Fix | Delete
self._filename = None
[204] Fix | Delete
self._startlineno = 0
[205] Fix | Delete
self._filelineno = 0
[206] Fix | Delete
self._file = None
[207] Fix | Delete
self._isstdin = False
[208] Fix | Delete
self._backupfilename = None
[209] Fix | Delete
# restrict mode argument to reading modes
[210] Fix | Delete
if mode not in ('r', 'rU', 'U', 'rb'):
[211] Fix | Delete
raise ValueError("FileInput opening mode must be one of "
[212] Fix | Delete
"'r', 'rU', 'U' and 'rb'")
[213] Fix | Delete
if 'U' in mode:
[214] Fix | Delete
import warnings
[215] Fix | Delete
warnings.warn("'U' mode is deprecated",
[216] Fix | Delete
DeprecationWarning, 2)
[217] Fix | Delete
self._mode = mode
[218] Fix | Delete
self._write_mode = mode.replace('r', 'w') if 'U' not in mode else 'w'
[219] Fix | Delete
if openhook:
[220] Fix | Delete
if inplace:
[221] Fix | Delete
raise ValueError("FileInput cannot use an opening hook in inplace mode")
[222] Fix | Delete
if not callable(openhook):
[223] Fix | Delete
raise ValueError("FileInput openhook must be callable")
[224] Fix | Delete
self._openhook = openhook
[225] Fix | Delete
[226] Fix | Delete
def __del__(self):
[227] Fix | Delete
self.close()
[228] Fix | Delete
[229] Fix | Delete
def close(self):
[230] Fix | Delete
try:
[231] Fix | Delete
self.nextfile()
[232] Fix | Delete
finally:
[233] Fix | Delete
self._files = ()
[234] Fix | Delete
[235] Fix | Delete
def __enter__(self):
[236] Fix | Delete
return self
[237] Fix | Delete
[238] Fix | Delete
def __exit__(self, type, value, traceback):
[239] Fix | Delete
self.close()
[240] Fix | Delete
[241] Fix | Delete
def __iter__(self):
[242] Fix | Delete
return self
[243] Fix | Delete
[244] Fix | Delete
def __next__(self):
[245] Fix | Delete
while True:
[246] Fix | Delete
line = self._readline()
[247] Fix | Delete
if line:
[248] Fix | Delete
self._filelineno += 1
[249] Fix | Delete
return line
[250] Fix | Delete
if not self._file:
[251] Fix | Delete
raise StopIteration
[252] Fix | Delete
self.nextfile()
[253] Fix | Delete
# repeat with next file
[254] Fix | Delete
[255] Fix | Delete
def __getitem__(self, i):
[256] Fix | Delete
import warnings
[257] Fix | Delete
warnings.warn(
[258] Fix | Delete
"Support for indexing FileInput objects is deprecated. "
[259] Fix | Delete
"Use iterator protocol instead.",
[260] Fix | Delete
DeprecationWarning,
[261] Fix | Delete
stacklevel=2
[262] Fix | Delete
)
[263] Fix | Delete
if i != self.lineno():
[264] Fix | Delete
raise RuntimeError("accessing lines out of order")
[265] Fix | Delete
try:
[266] Fix | Delete
return self.__next__()
[267] Fix | Delete
except StopIteration:
[268] Fix | Delete
raise IndexError("end of input reached")
[269] Fix | Delete
[270] Fix | Delete
def nextfile(self):
[271] Fix | Delete
savestdout = self._savestdout
[272] Fix | Delete
self._savestdout = None
[273] Fix | Delete
if savestdout:
[274] Fix | Delete
sys.stdout = savestdout
[275] Fix | Delete
[276] Fix | Delete
output = self._output
[277] Fix | Delete
self._output = None
[278] Fix | Delete
try:
[279] Fix | Delete
if output:
[280] Fix | Delete
output.close()
[281] Fix | Delete
finally:
[282] Fix | Delete
file = self._file
[283] Fix | Delete
self._file = None
[284] Fix | Delete
try:
[285] Fix | Delete
del self._readline # restore FileInput._readline
[286] Fix | Delete
except AttributeError:
[287] Fix | Delete
pass
[288] Fix | Delete
try:
[289] Fix | Delete
if file and not self._isstdin:
[290] Fix | Delete
file.close()
[291] Fix | Delete
finally:
[292] Fix | Delete
backupfilename = self._backupfilename
[293] Fix | Delete
self._backupfilename = None
[294] Fix | Delete
if backupfilename and not self._backup:
[295] Fix | Delete
try: os.unlink(backupfilename)
[296] Fix | Delete
except OSError: pass
[297] Fix | Delete
[298] Fix | Delete
self._isstdin = False
[299] Fix | Delete
[300] Fix | Delete
def readline(self):
[301] Fix | Delete
while True:
[302] Fix | Delete
line = self._readline()
[303] Fix | Delete
if line:
[304] Fix | Delete
self._filelineno += 1
[305] Fix | Delete
return line
[306] Fix | Delete
if not self._file:
[307] Fix | Delete
return line
[308] Fix | Delete
self.nextfile()
[309] Fix | Delete
# repeat with next file
[310] Fix | Delete
[311] Fix | Delete
def _readline(self):
[312] Fix | Delete
if not self._files:
[313] Fix | Delete
if 'b' in self._mode:
[314] Fix | Delete
return b''
[315] Fix | Delete
else:
[316] Fix | Delete
return ''
[317] Fix | Delete
self._filename = self._files[0]
[318] Fix | Delete
self._files = self._files[1:]
[319] Fix | Delete
self._startlineno = self.lineno()
[320] Fix | Delete
self._filelineno = 0
[321] Fix | Delete
self._file = None
[322] Fix | Delete
self._isstdin = False
[323] Fix | Delete
self._backupfilename = 0
[324] Fix | Delete
if self._filename == '-':
[325] Fix | Delete
self._filename = '<stdin>'
[326] Fix | Delete
if 'b' in self._mode:
[327] Fix | Delete
self._file = getattr(sys.stdin, 'buffer', sys.stdin)
[328] Fix | Delete
else:
[329] Fix | Delete
self._file = sys.stdin
[330] Fix | Delete
self._isstdin = True
[331] Fix | Delete
else:
[332] Fix | Delete
if self._inplace:
[333] Fix | Delete
self._backupfilename = (
[334] Fix | Delete
os.fspath(self._filename) + (self._backup or ".bak"))
[335] Fix | Delete
try:
[336] Fix | Delete
os.unlink(self._backupfilename)
[337] Fix | Delete
except OSError:
[338] Fix | Delete
pass
[339] Fix | Delete
# The next few lines may raise OSError
[340] Fix | Delete
os.rename(self._filename, self._backupfilename)
[341] Fix | Delete
self._file = open(self._backupfilename, self._mode)
[342] Fix | Delete
try:
[343] Fix | Delete
perm = os.fstat(self._file.fileno()).st_mode
[344] Fix | Delete
except OSError:
[345] Fix | Delete
self._output = open(self._filename, self._write_mode)
[346] Fix | Delete
else:
[347] Fix | Delete
mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC
[348] Fix | Delete
if hasattr(os, 'O_BINARY'):
[349] Fix | Delete
mode |= os.O_BINARY
[350] Fix | Delete
[351] Fix | Delete
fd = os.open(self._filename, mode, perm)
[352] Fix | Delete
self._output = os.fdopen(fd, self._write_mode)
[353] Fix | Delete
try:
[354] Fix | Delete
os.chmod(self._filename, perm)
[355] Fix | Delete
except OSError:
[356] Fix | Delete
pass
[357] Fix | Delete
self._savestdout = sys.stdout
[358] Fix | Delete
sys.stdout = self._output
[359] Fix | Delete
else:
[360] Fix | Delete
# This may raise OSError
[361] Fix | Delete
if self._openhook:
[362] Fix | Delete
self._file = self._openhook(self._filename, self._mode)
[363] Fix | Delete
else:
[364] Fix | Delete
self._file = open(self._filename, self._mode)
[365] Fix | Delete
self._readline = self._file.readline # hide FileInput._readline
[366] Fix | Delete
return self._readline()
[367] Fix | Delete
[368] Fix | Delete
def filename(self):
[369] Fix | Delete
return self._filename
[370] Fix | Delete
[371] Fix | Delete
def lineno(self):
[372] Fix | Delete
return self._startlineno + self._filelineno
[373] Fix | Delete
[374] Fix | Delete
def filelineno(self):
[375] Fix | Delete
return self._filelineno
[376] Fix | Delete
[377] Fix | Delete
def fileno(self):
[378] Fix | Delete
if self._file:
[379] Fix | Delete
try:
[380] Fix | Delete
return self._file.fileno()
[381] Fix | Delete
except ValueError:
[382] Fix | Delete
return -1
[383] Fix | Delete
else:
[384] Fix | Delete
return -1
[385] Fix | Delete
[386] Fix | Delete
def isfirstline(self):
[387] Fix | Delete
return self._filelineno == 1
[388] Fix | Delete
[389] Fix | Delete
def isstdin(self):
[390] Fix | Delete
return self._isstdin
[391] Fix | Delete
[392] Fix | Delete
[393] Fix | Delete
def hook_compressed(filename, mode):
[394] Fix | Delete
ext = os.path.splitext(filename)[1]
[395] Fix | Delete
if ext == '.gz':
[396] Fix | Delete
import gzip
[397] Fix | Delete
return gzip.open(filename, mode)
[398] Fix | Delete
elif ext == '.bz2':
[399] Fix | Delete
import bz2
[400] Fix | Delete
return bz2.BZ2File(filename, mode)
[401] Fix | Delete
else:
[402] Fix | Delete
return open(filename, mode)
[403] Fix | Delete
[404] Fix | Delete
[405] Fix | Delete
def hook_encoded(encoding, errors=None):
[406] Fix | Delete
def openhook(filename, mode):
[407] Fix | Delete
return open(filename, mode, encoding=encoding, errors=errors)
[408] Fix | Delete
return openhook
[409] Fix | Delete
[410] Fix | Delete
[411] Fix | Delete
def _test():
[412] Fix | Delete
import getopt
[413] Fix | Delete
inplace = False
[414] Fix | Delete
backup = False
[415] Fix | Delete
opts, args = getopt.getopt(sys.argv[1:], "ib:")
[416] Fix | Delete
for o, a in opts:
[417] Fix | Delete
if o == '-i': inplace = True
[418] Fix | Delete
if o == '-b': backup = a
[419] Fix | Delete
for line in input(args, inplace=inplace, backup=backup):
[420] Fix | Delete
if line[-1:] == '\n': line = line[:-1]
[421] Fix | Delete
if line[-1:] == '\r': line = line[:-1]
[422] Fix | Delete
print("%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
[423] Fix | Delete
isfirstline() and "*" or "", line))
[424] Fix | Delete
print("%d: %s[%d]" % (lineno(), filename(), filelineno()))
[425] Fix | Delete
[426] Fix | Delete
if __name__ == '__main__':
[427] Fix | Delete
_test()
[428] Fix | Delete
[429] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function