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
The function
os.listdir()only returns the file names, not the full paths, so you should useos.path.join()to add the directory names:(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.)