summaryrefslogtreecommitdiff
path: root/Lib/fileinput.py
diff options
context:
space:
mode:
Diffstat (limited to 'Lib/fileinput.py')
-rw-r--r--Lib/fileinput.py77
1 files changed, 43 insertions, 34 deletions
diff --git a/Lib/fileinput.py b/Lib/fileinput.py
index ba48575209..dbbbb2192e 100644
--- a/Lib/fileinput.py
+++ b/Lib/fileinput.py
@@ -81,16 +81,17 @@ XXX Possible additions:
import sys, os
-__all__ = ["input","close","nextfile","filename","lineno","filelineno",
- "isfirstline","isstdin","FileInput"]
+__all__ = ["input", "close", "nextfile", "filename", "lineno", "filelineno",
+ "isfirstline", "isstdin", "FileInput"]
_state = None
DEFAULT_BUFSIZE = 8*1024
-def input(files=None, inplace=0, backup="", bufsize=0,
+def input(files=None, inplace=False, backup="", bufsize=0,
mode="r", openhook=None):
- """input([files[, inplace[, backup[, mode[, openhook]]]]])
+ """input(files=None, inplace=False, backup="", bufsize=0, \
+mode="r", openhook=None)
Create an instance of the FileInput class. The instance will be used
as global state for the functions of this module, and is also returned
@@ -99,7 +100,7 @@ def input(files=None, inplace=0, backup="", bufsize=0,
"""
global _state
if _state and _state._file:
- raise RuntimeError, "input() already active"
+ raise RuntimeError("input() already active")
_state = FileInput(files, inplace, backup, bufsize, mode, openhook)
return _state
@@ -122,7 +123,7 @@ def nextfile():
last file has been read, this function has no effect.
"""
if not _state:
- raise RuntimeError, "no active input()"
+ raise RuntimeError("no active input()")
return _state.nextfile()
def filename():
@@ -131,7 +132,7 @@ def filename():
Before the first line has been read, returns None.
"""
if not _state:
- raise RuntimeError, "no active input()"
+ raise RuntimeError("no active input()")
return _state.filename()
def lineno():
@@ -141,7 +142,7 @@ def lineno():
of the last file has been read, returns the line number of that line.
"""
if not _state:
- raise RuntimeError, "no active input()"
+ raise RuntimeError("no active input()")
return _state.lineno()
def filelineno():
@@ -151,7 +152,7 @@ def filelineno():
been read, returns the line number of that line within the file.
"""
if not _state:
- raise RuntimeError, "no active input()"
+ raise RuntimeError("no active input()")
return _state.filelineno()
def fileno():
@@ -160,7 +161,7 @@ def fileno():
opened, returns -1.
"""
if not _state:
- raise RuntimeError, "no active input()"
+ raise RuntimeError("no active input()")
return _state.fileno()
def isfirstline():
@@ -169,7 +170,7 @@ def isfirstline():
otherwise returns false.
"""
if not _state:
- raise RuntimeError, "no active input()"
+ raise RuntimeError("no active input()")
return _state.isfirstline()
def isstdin():
@@ -178,7 +179,7 @@ def isstdin():
otherwise returns false.
"""
if not _state:
- raise RuntimeError, "no active input()"
+ raise RuntimeError("no active input()")
return _state.isstdin()
class FileInput:
@@ -194,9 +195,9 @@ class FileInput:
sequential order; random access and readline() cannot be mixed.
"""
- def __init__(self, files=None, inplace=0, backup="", bufsize=0,
+ def __init__(self, files=None, inplace=False, backup="", bufsize=0,
mode="r", openhook=None):
- if isinstance(files, basestring):
+ if isinstance(files, str):
files = (files,)
else:
if files is None:
@@ -224,10 +225,11 @@ class FileInput:
raise ValueError("FileInput opening mode must be one of "
"'r', 'rU', 'U' and 'rb'")
self._mode = mode
- if inplace and openhook:
- raise ValueError("FileInput cannot use an opening hook in inplace mode")
- elif openhook and not hasattr(openhook, '__call__'):
- raise ValueError("FileInput openhook must be callable")
+ if openhook:
+ if inplace:
+ raise ValueError("FileInput cannot use an opening hook in inplace mode")
+ if not callable(openhook):
+ raise ValueError("FileInput openhook must be callable")
self._openhook = openhook
def __del__(self):
@@ -237,10 +239,16 @@ class FileInput:
self.nextfile()
self._files = ()
+ def __enter__(self):
+ return self
+
+ def __exit__(self, type, value, traceback):
+ self.close()
+
def __iter__(self):
return self
- def next(self):
+ def __next__(self):
try:
line = self._buffer[self._bufindex]
except IndexError:
@@ -257,11 +265,11 @@ class FileInput:
def __getitem__(self, i):
if i != self._lineno:
- raise RuntimeError, "accessing lines out of order"
+ raise RuntimeError("accessing lines out of order")
try:
- return self.next()
+ return self.__next__()
except StopIteration:
- raise IndexError, "end of input reached"
+ raise IndexError("end of input reached")
def nextfile(self):
savestdout = self._savestdout
@@ -315,7 +323,7 @@ class FileInput:
else:
if self._inplace:
self._backupfilename = (
- self._filename + (self._backup or os.extsep+"bak"))
+ self._filename + (self._backup or ".bak"))
try: os.unlink(self._backupfilename)
except os.error: pass
# The next few lines may raise IOError
@@ -326,9 +334,11 @@ class FileInput:
except OSError:
self._output = open(self._filename, "w")
else:
- fd = os.open(self._filename,
- os.O_CREAT | os.O_WRONLY | os.O_TRUNC,
- perm)
+ mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC
+ if hasattr(os, 'O_BINARY'):
+ mode |= os.O_BINARY
+
+ fd = os.open(self._filename, mode, perm)
self._output = os.fdopen(fd, "w")
try:
if hasattr(os, 'chmod'):
@@ -388,26 +398,25 @@ def hook_compressed(filename, mode):
def hook_encoded(encoding):
- import codecs
def openhook(filename, mode):
- return codecs.open(filename, mode, encoding)
+ return open(filename, mode, encoding=encoding)
return openhook
def _test():
import getopt
- inplace = 0
- backup = 0
+ inplace = False
+ backup = False
opts, args = getopt.getopt(sys.argv[1:], "ib:")
for o, a in opts:
- if o == '-i': inplace = 1
+ if o == '-i': inplace = True
if o == '-b': backup = a
for line in input(args, inplace=inplace, backup=backup):
if line[-1:] == '\n': line = line[:-1]
if line[-1:] == '\r': line = line[:-1]
- print "%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
- isfirstline() and "*" or "", line)
- print "%d: %s[%d]" % (lineno(), filename(), filelineno())
+ print("%d: %s[%d]%s %s" % (lineno(), filename(), filelineno(),
+ isfirstline() and "*" or "", line))
+ print("%d: %s[%d]" % (lineno(), filename(), filelineno()))
if __name__ == '__main__':
_test()