Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/AnonR/anonr.TX.../opt/imh-pyth.../lib/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
from types import GenericAlias
[75] Fix | Delete
[76] Fix | Delete
__all__ = ["input", "close", "nextfile", "filename", "lineno", "filelineno",
[77] Fix | Delete
"fileno", "isfirstline", "isstdin", "FileInput", "hook_compressed",
[78] Fix | Delete
"hook_encoded"]
[79] Fix | Delete
[80] Fix | Delete
_state = None
[81] Fix | Delete
[82] Fix | Delete
def input(files=None, inplace=False, backup="", *, mode="r", openhook=None):
[83] Fix | Delete
"""Return an instance of the FileInput class, which can be iterated.
[84] Fix | Delete
[85] Fix | Delete
The parameters are passed to the constructor of the FileInput class.
[86] Fix | Delete
The returned instance, in addition to being an iterator,
[87] Fix | Delete
keeps global state for the functions of this module,.
[88] Fix | Delete
"""
[89] Fix | Delete
global _state
[90] Fix | Delete
if _state and _state._file:
[91] Fix | Delete
raise RuntimeError("input() already active")
[92] Fix | Delete
_state = FileInput(files, inplace, backup, mode=mode, openhook=openhook)
[93] Fix | Delete
return _state
[94] Fix | Delete
[95] Fix | Delete
def close():
[96] Fix | Delete
"""Close the sequence."""
[97] Fix | Delete
global _state
[98] Fix | Delete
state = _state
[99] Fix | Delete
_state = None
[100] Fix | Delete
if state:
[101] Fix | Delete
state.close()
[102] Fix | Delete
[103] Fix | Delete
def nextfile():
[104] Fix | Delete
"""
[105] Fix | Delete
Close the current file so that the next iteration will read the first
[106] Fix | Delete
line from the next file (if any); lines not read from the file will
[107] Fix | Delete
not count towards the cumulative line count. The filename is not
[108] Fix | Delete
changed until after the first line of the next file has been read.
[109] Fix | Delete
Before the first line has been read, this function has no effect;
[110] Fix | Delete
it cannot be used to skip the first file. After the last line of the
[111] Fix | Delete
last file has been read, this function has no effect.
[112] Fix | Delete
"""
[113] Fix | Delete
if not _state:
[114] Fix | Delete
raise RuntimeError("no active input()")
[115] Fix | Delete
return _state.nextfile()
[116] Fix | Delete
[117] Fix | Delete
def filename():
[118] Fix | Delete
"""
[119] Fix | Delete
Return the name of the file currently being read.
[120] Fix | Delete
Before the first line has been read, returns None.
[121] Fix | Delete
"""
[122] Fix | Delete
if not _state:
[123] Fix | Delete
raise RuntimeError("no active input()")
[124] Fix | Delete
return _state.filename()
[125] Fix | Delete
[126] Fix | Delete
def lineno():
[127] Fix | Delete
"""
[128] Fix | Delete
Return the cumulative line number of the line that has just been read.
[129] Fix | Delete
Before the first line has been read, returns 0. After the last line
[130] Fix | Delete
of the last file has been read, returns the line number of that line.
[131] Fix | Delete
"""
[132] Fix | Delete
if not _state:
[133] Fix | Delete
raise RuntimeError("no active input()")
[134] Fix | Delete
return _state.lineno()
[135] Fix | Delete
[136] Fix | Delete
def filelineno():
[137] Fix | Delete
"""
[138] Fix | Delete
Return the line number in the current file. Before the first line
[139] Fix | Delete
has been read, returns 0. After the last line of the last file has
[140] Fix | Delete
been read, returns the line number of that line within the file.
[141] Fix | Delete
"""
[142] Fix | Delete
if not _state:
[143] Fix | Delete
raise RuntimeError("no active input()")
[144] Fix | Delete
return _state.filelineno()
[145] Fix | Delete
[146] Fix | Delete
def fileno():
[147] Fix | Delete
"""
[148] Fix | Delete
Return the file number of the current file. When no file is currently
[149] Fix | Delete
opened, returns -1.
[150] Fix | Delete
"""
[151] Fix | Delete
if not _state:
[152] Fix | Delete
raise RuntimeError("no active input()")
[153] Fix | Delete
return _state.fileno()
[154] Fix | Delete
[155] Fix | Delete
def isfirstline():
[156] Fix | Delete
"""
[157] Fix | Delete
Returns true the line just read is the first line of its file,
[158] Fix | Delete
otherwise returns false.
[159] Fix | Delete
"""
[160] Fix | Delete
if not _state:
[161] Fix | Delete
raise RuntimeError("no active input()")
[162] Fix | Delete
return _state.isfirstline()
[163] Fix | Delete
[164] Fix | Delete
def isstdin():
[165] Fix | Delete
"""
[166] Fix | Delete
Returns true if the last line was read from sys.stdin,
[167] Fix | Delete
otherwise returns false.
[168] Fix | Delete
"""
[169] Fix | Delete
if not _state:
[170] Fix | Delete
raise RuntimeError("no active input()")
[171] Fix | Delete
return _state.isstdin()
[172] Fix | Delete
[173] Fix | Delete
class FileInput:
[174] Fix | Delete
"""FileInput([files[, inplace[, backup]]], *, mode=None, openhook=None)
[175] Fix | Delete
[176] Fix | Delete
Class FileInput is the implementation of the module; its methods
[177] Fix | Delete
filename(), lineno(), fileline(), isfirstline(), isstdin(), fileno(),
[178] Fix | Delete
nextfile() and close() correspond to the functions of the same name
[179] Fix | Delete
in the module.
[180] Fix | Delete
In addition it has a readline() method which returns the next
[181] Fix | Delete
input line, and a __getitem__() method which implements the
[182] Fix | Delete
sequence behavior. The sequence must be accessed in strictly
[183] Fix | Delete
sequential order; random access and readline() cannot be mixed.
[184] Fix | Delete
"""
[185] Fix | Delete
[186] Fix | Delete
def __init__(self, files=None, inplace=False, backup="", *,
[187] Fix | Delete
mode="r", openhook=None):
[188] Fix | Delete
if isinstance(files, str):
[189] Fix | Delete
files = (files,)
[190] Fix | Delete
elif isinstance(files, os.PathLike):
[191] Fix | Delete
files = (os.fspath(files), )
[192] Fix | Delete
else:
[193] Fix | Delete
if files is None:
[194] Fix | Delete
files = sys.argv[1:]
[195] Fix | Delete
if not files:
[196] Fix | Delete
files = ('-',)
[197] Fix | Delete
else:
[198] Fix | Delete
files = tuple(files)
[199] Fix | Delete
self._files = files
[200] Fix | Delete
self._inplace = inplace
[201] Fix | Delete
self._backup = backup
[202] Fix | Delete
self._savestdout = None
[203] Fix | Delete
self._output = None
[204] Fix | Delete
self._filename = None
[205] Fix | Delete
self._startlineno = 0
[206] Fix | Delete
self._filelineno = 0
[207] Fix | Delete
self._file = None
[208] Fix | Delete
self._isstdin = False
[209] Fix | Delete
self._backupfilename = None
[210] Fix | Delete
# restrict mode argument to reading modes
[211] Fix | Delete
if mode not in ('r', 'rU', 'U', 'rb'):
[212] Fix | Delete
raise ValueError("FileInput opening mode must be one of "
[213] Fix | Delete
"'r', 'rU', 'U' and 'rb'")
[214] Fix | Delete
if 'U' in mode:
[215] Fix | Delete
import warnings
[216] Fix | Delete
warnings.warn("'U' mode is deprecated",
[217] Fix | Delete
DeprecationWarning, 2)
[218] Fix | Delete
self._mode = mode
[219] Fix | Delete
self._write_mode = mode.replace('r', 'w') if 'U' not in mode else 'w'
[220] Fix | Delete
if openhook:
[221] Fix | Delete
if inplace:
[222] Fix | Delete
raise ValueError("FileInput cannot use an opening hook in inplace mode")
[223] Fix | Delete
if not callable(openhook):
[224] Fix | Delete
raise ValueError("FileInput openhook must be callable")
[225] Fix | Delete
self._openhook = openhook
[226] Fix | Delete
[227] Fix | Delete
def __del__(self):
[228] Fix | Delete
self.close()
[229] Fix | Delete
[230] Fix | Delete
def close(self):
[231] Fix | Delete
try:
[232] Fix | Delete
self.nextfile()
[233] Fix | Delete
finally:
[234] Fix | Delete
self._files = ()
[235] Fix | Delete
[236] Fix | Delete
def __enter__(self):
[237] Fix | Delete
return self
[238] Fix | Delete
[239] Fix | Delete
def __exit__(self, type, value, traceback):
[240] Fix | Delete
self.close()
[241] Fix | Delete
[242] Fix | Delete
def __iter__(self):
[243] Fix | Delete
return self
[244] Fix | Delete
[245] Fix | Delete
def __next__(self):
[246] Fix | Delete
while True:
[247] Fix | Delete
line = self._readline()
[248] Fix | Delete
if line:
[249] Fix | Delete
self._filelineno += 1
[250] Fix | Delete
return line
[251] Fix | Delete
if not self._file:
[252] Fix | Delete
raise StopIteration
[253] Fix | Delete
self.nextfile()
[254] Fix | Delete
# repeat with next file
[255] Fix | Delete
[256] Fix | Delete
def __getitem__(self, i):
[257] Fix | Delete
import warnings
[258] Fix | Delete
warnings.warn(
[259] Fix | Delete
"Support for indexing FileInput objects is deprecated. "
[260] Fix | Delete
"Use iterator protocol instead.",
[261] Fix | Delete
DeprecationWarning,
[262] Fix | Delete
stacklevel=2
[263] Fix | Delete
)
[264] Fix | Delete
if i != self.lineno():
[265] Fix | Delete
raise RuntimeError("accessing lines out of order")
[266] Fix | Delete
try:
[267] Fix | Delete
return self.__next__()
[268] Fix | Delete
except StopIteration:
[269] Fix | Delete
raise IndexError("end of input reached")
[270] Fix | Delete
[271] Fix | Delete
def nextfile(self):
[272] Fix | Delete
savestdout = self._savestdout
[273] Fix | Delete
self._savestdout = None
[274] Fix | Delete
if savestdout:
[275] Fix | Delete
sys.stdout = savestdout
[276] Fix | Delete
[277] Fix | Delete
output = self._output
[278] Fix | Delete
self._output = None
[279] Fix | Delete
try:
[280] Fix | Delete
if output:
[281] Fix | Delete
output.close()
[282] Fix | Delete
finally:
[283] Fix | Delete
file = self._file
[284] Fix | Delete
self._file = None
[285] Fix | Delete
try:
[286] Fix | Delete
del self._readline # restore FileInput._readline
[287] Fix | Delete
except AttributeError:
[288] Fix | Delete
pass
[289] Fix | Delete
try:
[290] Fix | Delete
if file and not self._isstdin:
[291] Fix | Delete
file.close()
[292] Fix | Delete
finally:
[293] Fix | Delete
backupfilename = self._backupfilename
[294] Fix | Delete
self._backupfilename = None
[295] Fix | Delete
if backupfilename and not self._backup:
[296] Fix | Delete
try: os.unlink(backupfilename)
[297] Fix | Delete
except OSError: pass
[298] Fix | Delete
[299] Fix | Delete
self._isstdin = False
[300] Fix | Delete
[301] Fix | Delete
def readline(self):
[302] Fix | Delete
while True:
[303] Fix | Delete
line = self._readline()
[304] Fix | Delete
if line:
[305] Fix | Delete
self._filelineno += 1
[306] Fix | Delete
return line
[307] Fix | Delete
if not self._file:
[308] Fix | Delete
return line
[309] Fix | Delete
self.nextfile()
[310] Fix | Delete
# repeat with next file
[311] Fix | Delete
[312] Fix | Delete
def _readline(self):
[313] Fix | Delete
if not self._files:
[314] Fix | Delete
if 'b' in self._mode:
[315] Fix | Delete
return b''
[316] Fix | Delete
else:
[317] Fix | Delete
return ''
[318] Fix | Delete
self._filename = self._files[0]
[319] Fix | Delete
self._files = self._files[1:]
[320] Fix | Delete
self._startlineno = self.lineno()
[321] Fix | Delete
self._filelineno = 0
[322] Fix | Delete
self._file = None
[323] Fix | Delete
self._isstdin = False
[324] Fix | Delete
self._backupfilename = 0
[325] Fix | Delete
if self._filename == '-':
[326] Fix | Delete
self._filename = '<stdin>'
[327] Fix | Delete
if 'b' in self._mode:
[328] Fix | Delete
self._file = getattr(sys.stdin, 'buffer', sys.stdin)
[329] Fix | Delete
else:
[330] Fix | Delete
self._file = sys.stdin
[331] Fix | Delete
self._isstdin = True
[332] Fix | Delete
else:
[333] Fix | Delete
if self._inplace:
[334] Fix | Delete
self._backupfilename = (
[335] Fix | Delete
os.fspath(self._filename) + (self._backup or ".bak"))
[336] Fix | Delete
try:
[337] Fix | Delete
os.unlink(self._backupfilename)
[338] Fix | Delete
except OSError:
[339] Fix | Delete
pass
[340] Fix | Delete
# The next few lines may raise OSError
[341] Fix | Delete
os.rename(self._filename, self._backupfilename)
[342] Fix | Delete
self._file = open(self._backupfilename, self._mode)
[343] Fix | Delete
try:
[344] Fix | Delete
perm = os.fstat(self._file.fileno()).st_mode
[345] Fix | Delete
except OSError:
[346] Fix | Delete
self._output = open(self._filename, self._write_mode)
[347] Fix | Delete
else:
[348] Fix | Delete
mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC
[349] Fix | Delete
if hasattr(os, 'O_BINARY'):
[350] Fix | Delete
mode |= os.O_BINARY
[351] Fix | Delete
[352] Fix | Delete
fd = os.open(self._filename, mode, perm)
[353] Fix | Delete
self._output = os.fdopen(fd, self._write_mode)
[354] Fix | Delete
try:
[355] Fix | Delete
os.chmod(self._filename, perm)
[356] Fix | Delete
except OSError:
[357] Fix | Delete
pass
[358] Fix | Delete
self._savestdout = sys.stdout
[359] Fix | Delete
sys.stdout = self._output
[360] Fix | Delete
else:
[361] Fix | Delete
# This may raise OSError
[362] Fix | Delete
if self._openhook:
[363] Fix | Delete
self._file = self._openhook(self._filename, self._mode)
[364] Fix | Delete
else:
[365] Fix | Delete
self._file = open(self._filename, self._mode)
[366] Fix | Delete
self._readline = self._file.readline # hide FileInput._readline
[367] Fix | Delete
return self._readline()
[368] Fix | Delete
[369] Fix | Delete
def filename(self):
[370] Fix | Delete
return self._filename
[371] Fix | Delete
[372] Fix | Delete
def lineno(self):
[373] Fix | Delete
return self._startlineno + self._filelineno
[374] Fix | Delete
[375] Fix | Delete
def filelineno(self):
[376] Fix | Delete
return self._filelineno
[377] Fix | Delete
[378] Fix | Delete
def fileno(self):
[379] Fix | Delete
if self._file:
[380] Fix | Delete
try:
[381] Fix | Delete
return self._file.fileno()
[382] Fix | Delete
except ValueError:
[383] Fix | Delete
return -1
[384] Fix | Delete
else:
[385] Fix | Delete
return -1
[386] Fix | Delete
[387] Fix | Delete
def isfirstline(self):
[388] Fix | Delete
return self._filelineno == 1
[389] Fix | Delete
[390] Fix | Delete
def isstdin(self):
[391] Fix | Delete
return self._isstdin
[392] Fix | Delete
[393] Fix | Delete
__class_getitem__ = classmethod(GenericAlias)
[394] Fix | Delete
[395] Fix | Delete
[396] Fix | Delete
def hook_compressed(filename, mode):
[397] Fix | Delete
ext = os.path.splitext(filename)[1]
[398] Fix | Delete
if ext == '.gz':
[399] Fix | Delete
import gzip
[400] Fix | Delete
return gzip.open(filename, mode)
[401] Fix | Delete
elif ext == '.bz2':
[402] Fix | Delete
import bz2
[403] Fix | Delete
return bz2.BZ2File(filename, mode)
[404] Fix | Delete
else:
[405] Fix | Delete
return open(filename, mode)
[406] Fix | Delete
[407] Fix | Delete
[408] Fix | Delete
def hook_encoded(encoding, errors=None):
[409] Fix | Delete
def openhook(filename, mode):
[410] Fix | Delete
return open(filename, mode, encoding=encoding, errors=errors)
[411] Fix | Delete
return openhook
[412] Fix | Delete
[413] Fix | Delete
[414] Fix | Delete
def _test():
[415] Fix | Delete
import getopt
[416] Fix | Delete
inplace = False
[417] Fix | Delete
backup = False
[418] Fix | Delete
opts, args = getopt.getopt(sys.argv[1:], "ib:")
[419] Fix | Delete
for o, a in opts:
[420] Fix | Delete
if o == '-i': inplace = True
[421] Fix | Delete
if o == '-b': backup = a
[422] Fix | Delete
for line in input(args, inplace=inplace, backup=backup):
[423] Fix | Delete
if line[-1:] == '\n': line = line[:-1]
[424] Fix | Delete
if line[-1:] == '\r': line = line[:-1]
[425] Fix | Delete
print("%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
[426] Fix | Delete
isfirstline() and "*" or "", line))
[427] Fix | Delete
print("%d: %s[%d]" % (lineno(), filename(), filelineno()))
[428] Fix | Delete
[429] Fix | Delete
if __name__ == '__main__':
[430] Fix | Delete
_test()
[431] Fix | Delete
[432] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function