I need to read a sequence of files and fileinput
seemed just what was needed but then I realized it lacks a read
method.
- What is the canonical way (if any) to do this? (Explicit catenation will be wasteful.)
- Is there a known technical or security reason that
fileinput
does not supportread
?
This related question is not a duplicate.
Advertisement
Answer
Since they’re going to all be read into memory at once, you can make use of the io.StringIO
class
JavaScript
x
25
25
1
import io
2
3
4
class Filelike:
5
def __init__(self, filenames):
6
self.data = io.StringIO()
7
for filename in filenames:
8
with open(filename) as file:
9
self.data.write(file.read())
10
11
self.data.seek(0) # Rewind.
12
13
def read(self):
14
return self.data.getvalue()
15
16
17
if __name__ == '__main__':
18
19
filenames = ['file1.txt', 'file2.txt', ]
20
filelike = Filelike(filenames)
21
22
# process lines
23
for line in filelike.read().splitlines():
24
print(repr(line))
25