Edit File by line
/home/barbar84/www/wp-conte.../plugins/sujqvwi/ShExBy/shex_roo.../proc/self/root/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. To specify an alternative list of
[10] Fix | Delete
filenames, pass it as the argument to input(). A single file name is
[11] Fix | Delete
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="", bufsize=0,
[82] Fix | Delete
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, bufsize, mode, 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[, bufsize, [, mode[, openhook]]]]]])
[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="", bufsize=0,
[187] Fix | Delete
mode="r", openhook=None):
[188] Fix | Delete
if isinstance(files, str):
[189] Fix | Delete
files = (files,)
[190] Fix | Delete
else:
[191] Fix | Delete
if files is None:
[192] Fix | Delete
files = sys.argv[1:]
[193] Fix | Delete
if not files:
[194] Fix | Delete
files = ('-',)
[195] Fix | Delete
else:
[196] Fix | Delete
files = tuple(files)
[197] Fix | Delete
self._files = files
[198] Fix | Delete
self._inplace = inplace
[199] Fix | Delete
self._backup = backup
[200] Fix | Delete
if bufsize:
[201] Fix | Delete
import warnings
[202] Fix | Delete
warnings.warn('bufsize is deprecated and ignored',
[203] Fix | Delete
DeprecationWarning, stacklevel=2)
[204] Fix | Delete
self._savestdout = None
[205] Fix | Delete
self._output = None
[206] Fix | Delete
self._filename = None
[207] Fix | Delete
self._startlineno = 0
[208] Fix | Delete
self._filelineno = 0
[209] Fix | Delete
self._file = None
[210] Fix | Delete
self._isstdin = False
[211] Fix | Delete
self._backupfilename = None
[212] Fix | Delete
# restrict mode argument to reading modes
[213] Fix | Delete
if mode not in ('r', 'rU', 'U', 'rb'):
[214] Fix | Delete
raise ValueError("FileInput opening mode must be one of "
[215] Fix | Delete
"'r', 'rU', 'U' and 'rb'")
[216] Fix | Delete
if 'U' in mode:
[217] Fix | Delete
import warnings
[218] Fix | Delete
warnings.warn("'U' mode is deprecated",
[219] Fix | Delete
DeprecationWarning, 2)
[220] Fix | Delete
self._mode = mode
[221] Fix | Delete
if openhook:
[222] Fix | Delete
if inplace:
[223] Fix | Delete
raise ValueError("FileInput cannot use an opening hook in inplace mode")
[224] Fix | Delete
if not callable(openhook):
[225] Fix | Delete
raise ValueError("FileInput openhook must be callable")
[226] Fix | Delete
self._openhook = openhook
[227] Fix | Delete
[228] Fix | Delete
def __del__(self):
[229] Fix | Delete
self.close()
[230] Fix | Delete
[231] Fix | Delete
def close(self):
[232] Fix | Delete
try:
[233] Fix | Delete
self.nextfile()
[234] Fix | Delete
finally:
[235] Fix | Delete
self._files = ()
[236] Fix | Delete
[237] Fix | Delete
def __enter__(self):
[238] Fix | Delete
return self
[239] Fix | Delete
[240] Fix | Delete
def __exit__(self, type, value, traceback):
[241] Fix | Delete
self.close()
[242] Fix | Delete
[243] Fix | Delete
def __iter__(self):
[244] Fix | Delete
return self
[245] Fix | Delete
[246] Fix | Delete
def __next__(self):
[247] Fix | Delete
while True:
[248] Fix | Delete
line = self._readline()
[249] Fix | Delete
if line:
[250] Fix | Delete
self._filelineno += 1
[251] Fix | Delete
return line
[252] Fix | Delete
if not self._file:
[253] Fix | Delete
raise StopIteration
[254] Fix | Delete
self.nextfile()
[255] Fix | Delete
# repeat with next file
[256] Fix | Delete
[257] Fix | Delete
def __getitem__(self, i):
[258] Fix | Delete
if i != self.lineno():
[259] Fix | Delete
raise RuntimeError("accessing lines out of order")
[260] Fix | Delete
try:
[261] Fix | Delete
return self.__next__()
[262] Fix | Delete
except StopIteration:
[263] Fix | Delete
raise IndexError("end of input reached")
[264] Fix | Delete
[265] Fix | Delete
def nextfile(self):
[266] Fix | Delete
savestdout = self._savestdout
[267] Fix | Delete
self._savestdout = None
[268] Fix | Delete
if savestdout:
[269] Fix | Delete
sys.stdout = savestdout
[270] Fix | Delete
[271] Fix | Delete
output = self._output
[272] Fix | Delete
self._output = None
[273] Fix | Delete
try:
[274] Fix | Delete
if output:
[275] Fix | Delete
output.close()
[276] Fix | Delete
finally:
[277] Fix | Delete
file = self._file
[278] Fix | Delete
self._file = None
[279] Fix | Delete
try:
[280] Fix | Delete
del self._readline # restore FileInput._readline
[281] Fix | Delete
except AttributeError:
[282] Fix | Delete
pass
[283] Fix | Delete
try:
[284] Fix | Delete
if file and not self._isstdin:
[285] Fix | Delete
file.close()
[286] Fix | Delete
finally:
[287] Fix | Delete
backupfilename = self._backupfilename
[288] Fix | Delete
self._backupfilename = None
[289] Fix | Delete
if backupfilename and not self._backup:
[290] Fix | Delete
try: os.unlink(backupfilename)
[291] Fix | Delete
except OSError: pass
[292] Fix | Delete
[293] Fix | Delete
self._isstdin = False
[294] Fix | Delete
[295] Fix | Delete
def readline(self):
[296] Fix | Delete
while True:
[297] Fix | Delete
line = self._readline()
[298] Fix | Delete
if line:
[299] Fix | Delete
self._filelineno += 1
[300] Fix | Delete
return line
[301] Fix | Delete
if not self._file:
[302] Fix | Delete
return line
[303] Fix | Delete
self.nextfile()
[304] Fix | Delete
# repeat with next file
[305] Fix | Delete
[306] Fix | Delete
def _readline(self):
[307] Fix | Delete
if not self._files:
[308] Fix | Delete
if 'b' in self._mode:
[309] Fix | Delete
return b''
[310] Fix | Delete
else:
[311] Fix | Delete
return ''
[312] Fix | Delete
self._filename = self._files[0]
[313] Fix | Delete
self._files = self._files[1:]
[314] Fix | Delete
self._startlineno = self.lineno()
[315] Fix | Delete
self._filelineno = 0
[316] Fix | Delete
self._file = None
[317] Fix | Delete
self._isstdin = False
[318] Fix | Delete
self._backupfilename = 0
[319] Fix | Delete
if self._filename == '-':
[320] Fix | Delete
self._filename = '<stdin>'
[321] Fix | Delete
if 'b' in self._mode:
[322] Fix | Delete
self._file = getattr(sys.stdin, 'buffer', sys.stdin)
[323] Fix | Delete
else:
[324] Fix | Delete
self._file = sys.stdin
[325] Fix | Delete
self._isstdin = True
[326] Fix | Delete
else:
[327] Fix | Delete
if self._inplace:
[328] Fix | Delete
self._backupfilename = (
[329] Fix | Delete
self._filename + (self._backup or ".bak"))
[330] Fix | Delete
try:
[331] Fix | Delete
os.unlink(self._backupfilename)
[332] Fix | Delete
except OSError:
[333] Fix | Delete
pass
[334] Fix | Delete
# The next few lines may raise OSError
[335] Fix | Delete
os.rename(self._filename, self._backupfilename)
[336] Fix | Delete
self._file = open(self._backupfilename, self._mode)
[337] Fix | Delete
try:
[338] Fix | Delete
perm = os.fstat(self._file.fileno()).st_mode
[339] Fix | Delete
except OSError:
[340] Fix | Delete
self._output = open(self._filename, "w")
[341] Fix | Delete
else:
[342] Fix | Delete
mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC
[343] Fix | Delete
if hasattr(os, 'O_BINARY'):
[344] Fix | Delete
mode |= os.O_BINARY
[345] Fix | Delete
[346] Fix | Delete
fd = os.open(self._filename, mode, perm)
[347] Fix | Delete
self._output = os.fdopen(fd, "w")
[348] Fix | Delete
try:
[349] Fix | Delete
if hasattr(os, 'chmod'):
[350] Fix | Delete
os.chmod(self._filename, perm)
[351] Fix | Delete
except OSError:
[352] Fix | Delete
pass
[353] Fix | Delete
self._savestdout = sys.stdout
[354] Fix | Delete
sys.stdout = self._output
[355] Fix | Delete
else:
[356] Fix | Delete
# This may raise OSError
[357] Fix | Delete
if self._openhook:
[358] Fix | Delete
self._file = self._openhook(self._filename, self._mode)
[359] Fix | Delete
else:
[360] Fix | Delete
self._file = open(self._filename, self._mode)
[361] Fix | Delete
self._readline = self._file.readline # hide FileInput._readline
[362] Fix | Delete
return self._readline()
[363] Fix | Delete
[364] Fix | Delete
def filename(self):
[365] Fix | Delete
return self._filename
[366] Fix | Delete
[367] Fix | Delete
def lineno(self):
[368] Fix | Delete
return self._startlineno + self._filelineno
[369] Fix | Delete
[370] Fix | Delete
def filelineno(self):
[371] Fix | Delete
return self._filelineno
[372] Fix | Delete
[373] Fix | Delete
def fileno(self):
[374] Fix | Delete
if self._file:
[375] Fix | Delete
try:
[376] Fix | Delete
return self._file.fileno()
[377] Fix | Delete
except ValueError:
[378] Fix | Delete
return -1
[379] Fix | Delete
else:
[380] Fix | Delete
return -1
[381] Fix | Delete
[382] Fix | Delete
def isfirstline(self):
[383] Fix | Delete
return self._filelineno == 1
[384] Fix | Delete
[385] Fix | Delete
def isstdin(self):
[386] Fix | Delete
return self._isstdin
[387] Fix | Delete
[388] Fix | Delete
[389] Fix | Delete
def hook_compressed(filename, mode):
[390] Fix | Delete
ext = os.path.splitext(filename)[1]
[391] Fix | Delete
if ext == '.gz':
[392] Fix | Delete
import gzip
[393] Fix | Delete
return gzip.open(filename, mode)
[394] Fix | Delete
elif ext == '.bz2':
[395] Fix | Delete
import bz2
[396] Fix | Delete
return bz2.BZ2File(filename, mode)
[397] Fix | Delete
else:
[398] Fix | Delete
return open(filename, mode)
[399] Fix | Delete
[400] Fix | Delete
[401] Fix | Delete
def hook_encoded(encoding, errors=None):
[402] Fix | Delete
def openhook(filename, mode):
[403] Fix | Delete
return open(filename, mode, encoding=encoding, errors=errors)
[404] Fix | Delete
return openhook
[405] Fix | Delete
[406] Fix | Delete
[407] Fix | Delete
def _test():
[408] Fix | Delete
import getopt
[409] Fix | Delete
inplace = False
[410] Fix | Delete
backup = False
[411] Fix | Delete
opts, args = getopt.getopt(sys.argv[1:], "ib:")
[412] Fix | Delete
for o, a in opts:
[413] Fix | Delete
if o == '-i': inplace = True
[414] Fix | Delete
if o == '-b': backup = a
[415] Fix | Delete
for line in input(args, inplace=inplace, backup=backup):
[416] Fix | Delete
if line[-1:] == '\n': line = line[:-1]
[417] Fix | Delete
if line[-1:] == '\r': line = line[:-1]
[418] Fix | Delete
print("%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
[419] Fix | Delete
isfirstline() and "*" or "", line))
[420] Fix | Delete
print("%d: %s[%d]" % (lineno(), filename(), filelineno()))
[421] Fix | Delete
[422] Fix | Delete
if __name__ == '__main__':
[423] Fix | Delete
_test()
[424] Fix | Delete
[425] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function