Reputation: 660
I have list of files in path, to which i want to create iter objects, so i can read from any file at any time, while all files are being open. Number of files in the path are dynamic.
filehandles = []
for filename in glob.glob(path):
filehandles += [open(filename, 'r')]
print(filehandles)
The below code throwing compile error, while calling next()
() missing 1 required positional argument: 'filehandle'
for filehandle in filehandles:
fileiters += [iter(lambda filehandle: filehandle.readline(), '')]
print(next(fileiters[2])(filehandles[3]))
If i dont keep any parameter to lambda, it is taking the last filehandle in the loop for all filehandles.
Can someone help in how do create iter over all the open files and call next selectively?
Upvotes: 0
Views: 98
Reputation: 104752
File objects are already iterators. I'm not sure I understand what you were trying to print
at the end of your example code, but you should be able to do print(next(filehandles[3]))
already (to print the next line in the fourth file in your list).
While it's probably unnecessary here, if you need to solve the general issue with lambda functions being created in a loop in the future, the general way to do it is to add a default value to the parameter:
functions = []
for x in lst:
functions.append(lambda x=x: x.foo())
The default argument is eagerly bound to the function object, so it preserves the value that x
had at the time the lambda expression was evaluated.
Upvotes: 1