Reputation: 2257
I have directory poem
which contains 50 files and I want to read them all.
for file in os.listdir("/home/ubuntu/Desktop/temp/poem"):
print file
f = open(file, 'r')
print f.read()
f.close()
This code reads file name of all the files in directory. But it fails at
f = open(file, 'r')
saying
IOError: [Errno 2] No such file or directory: '32'
Upvotes: 0
Views: 7374
Reputation: 2286
you are searching file in current join file path with directory folder.
import os
for i in os.listdir("/home/ubuntu/Desktop/temp/poem"):
if os.path.isfile(os.path.join("/home/ubuntu/Desktop/temp/poem",i)):
print os.path.join("/home/ubuntu/Desktop/temp/poem",i)
f=open(os.path.join("/home/ubuntu/Desktop/temp/poem",i),"r")
print f.readlines()
f.close()
Upvotes: 1
Reputation: 9969
os.listdir
only returns filenames, to get the full path you need to join that filename with the folder you're reading:
folder = "/home/ubuntu/Desktop/temp/poem"
for file in os.listdir(folder):
print file
filepath = os.path.join(folder, file)
f = open(filepath, 'r')
print f.read()
f.close()
Upvotes: 10