Reputation: 459
I am trying to read files, inside a folder, reason is the number of files inside the folder is not fixed, but if there are 3 text folder, I have to read all the 3 files if 4 all the 4 text files.
Here is the code I'm trying to use, but comes up with an IOError:
for i in os.listdir("./RecordFolder"):
print i
Output is: record1.txt record2.txt
Now the problem is reading the files:
for files in os.listdir("./RecordFolder"):
filecontent = open(files).readlines()
for lines in filecontent:
print lines
Output:
IOError: [Errno 2] No such file or directory: 'record.txt'
Need some help here, thanks
Upvotes: 0
Views: 320
Reputation: 602715
The function os.listdir()
only returns the file names, not the full paths, so you should use os.path.join()
to add the directory names:
directory = "./RecordFolder"
for filename in os.listdir(directory):
with open(os.path.join(directory, filename)) as f:
for line in f:
print line
(Also note that you shouldn't use file.readlines()
for simply iterating over the lines of the files, and that your code fails to close the file. These problems are fixed in the code above.)
Upvotes: 10
Reputation: 310287
os.listdir
only returns the name of the files inside the folder. Not the entire path.
You want something like:
directory = os.path.join(os.curdir, "RecordFolder")
for files in os.listdir(directory):
filecontent = open( os.path.join(directory, files) ).readlines()
for lines in filecontent:
print lines
But this isn't the best way to get the lines from a file. Look into python context managers -- specifically:
with open(filename) as f:
for line in f:
print line
This makes sure that the file is properly closed (even in the event of an error -- barring a segmentation fault in the interpreter itself or something bizarre like that).
Upvotes: 2