Ayush Kalani Ayush Kalani - 2 months ago 9
Python Question

OSError file not found when navigating through sub-directories in python?

There is a directory tree structure such that article is main folder and d10x are the subfolders

/articles
/d101
1.txt 2.txt 3.txt
/d102
1.txt 2.txt 3.txt
/d103
1.txt 2.txt 3.txt
/d104
.....
.....
.....
/d200


My program has to go to each of the subfolder and read a text file from it.

My python implementation gets the following error

OSError: [Errno 2] No such file or directory: 'd101'

Python code:


articles = os.listdir("articles")
mo=[]
for yo in articles:
mo.append(yo)
for index in range(len(mo)):
yo=os.listdir(mo[index])
for article in yo:
print 'Reading articles/' + article


OSError: [Errno 2] No such file or directory: 'd101'

Answer

You are trying to read d101 instead of articles/d101. Change your listdir() call to this:

os.listdir(os.path.join("articles", mo[index]))