Reputation: 541
I want to open and read all csv file in a specific folder. I'm on OS X El Capitan version 10.11.6, and I'm using Python 2.7.10. I have the following function in phyton file:
def open_csv_files(dir):
for root,dirs,files in os.walk(dir):
for file in files:
if file.endswith(".csv"):
f= open(file)
print "FILE OPEN, AND DO SOMETHING... "
f.close
return
I call open_csv_file(./dati/esempi)
This procedure return
IOError: [Errno 2] No such file or directory: 'sensorfile_1.csv'
I try to call the procedure with absolute path /Users/Claudia/Desktop/Thesis/dati/esempi/
but I have the same error.
Moreover I define another procedure that print all filename in folder, this procedure print correctly all filenames in folder.
Thanks for the help.
Upvotes: 0
Views: 3425
Reputation: 23203
You need to build absolute path to file based on values of root
(base dir) and file name.
import os
def open_csv_files(directory):
for root, dirs, files in os.walk(directory):
for file_name in files:
if file_name.endswith(".csv"):
full_file_path = os.path.join(root, file_name)
with open(full_file_path) as fh:
print "Do something with", full_file_path
Upvotes: 5