Python: Linecache Not Working As Expected?
Hello I have this python script that I need to use to traverse some directories and extract some info within some files within those directories. So I have many directories. Within
Solution 1:
It's possible linecache
is messing with you and actually caching
the line from a similarly named file from last time.
Also, it looks like you're not using the full filepath so you may be opening a different file than what you expect.
For example, instead of using f_v
you'll want to do something like:
filepath = os.path.join(<dirname>, <filename>)
Try replacing linecache.getline
with something like:
defget_line(filename, n):
withopen(filename, 'r') as f:
for line_number, line inenumerate(f):
if line_number == n:
return line
Unlike linecache this will actually open the file and read it each time.
Finally, this code would likely be much clearer and easier to deal with if you rewrote it using os.walk
:
https://docs.python.org/2/library/os.html
For example:
import os
for root, dirs, files in os.walk('someplace'):
fordirindirs:
# do something with the dirsfor file in files:
# do whatever with the files
Post a Comment for "Python: Linecache Not Working As Expected?"