Reputation: 59
So I have this small python script that I'm using to validate whether or not a folder contains csv files. I have it working so far but I'm trying to print the CSV file from the result list of csv files to the console.
import os
import logging
import csv
logger = logging.getLogger()
logger.setLevel(logging.INFO)
files = []
source = '/Users/username/source_folder'
files = checkFile(source)
if len(files) != 0:
for i in files:
with open(i, newline='') as file:
for row in csv.reader(file):
print(row)
def checkFile(directory):
result = []
if len(os.listdir(directory)) == 0:
return result
else:
for file in os.listdir(directory):
if file.endswith('.csv'):
result.append(file)
else:
continue
return result
I keep getting this error:
FileNotFoundError: [Errno 2] No such file or directory:
So the result is something like this: ['test_01.csv','test_02.csv']
But I would like to read the each file from the list to the console.
test_01.csv
id,first_name,last_name,phone,
1,joe,black,555555555
2,jack,flash,1111111111
test_02.csv
id,first_name,last_name,phone,
1,joe,black,555555555
2,jack,flash,1111111111
Upvotes: 1
Views: 101
Reputation: 144
os.listdir(...)
returns the file/sub-folder names only (not the full paths). Unless the csv files are in your current working directory, you will need to combine their names with the directory, e.g. with os.path.join(...)
:
def checkFile(directory):
result = []
if len(os.listdir(directory)) == 0:
return result
else:
for file in os.listdir(directory):
if file.endswith('.csv'):
result.append(os.path.join(directory, file))
else:
continue
return result
Upvotes: 1