Search code examples
pythonfile-not-foundpython-oslistdir

How to read a content of a file obtained from os.listdir?


I am trying to read a CSV file. I have two CSVs under two folders. I get the CSV file but when I try to read the content, it says that I dont have such file or directory.

import os
import csv

def scanCSVFile(folder, output_file_name):
    myfile = open(output_file_name, "a")
    files = os.listdir(folder)
    for file in files:
        if file.endswith('.csv'): #gives two csv files
            with open(file) as csvfile: 
                csvreader = csv.reader(csvfile)
                next(csvreader)
                for line in csvreader:
                    print (line)

    myfile.close()


def openCSV(path):
    scanCSVFile("./src/goi","goi.yml")
    scanCSVFile("./src/kanji","kanji.yml")

openCSV('.')

Error:

C:\Users\Peace\Documents\LMS>python csvToYaml.py 
Traceback (most recent call last): 
File "csvToYaml.py", line 26, in <module> openCSV('.') 
File "csvToYaml.py", line 24, in openCSV scanCSVFile("./src/goi","goi.yml") 
File "csvToYaml.py", line 14, in scanCSVFile with open(file) as csvfile:  
FileNotFoundError: [Errno 2] No such file or directory: 'Pro.csv'

Solution

  • You have to delete break from code

    import os,glob
    
    folder_path = r'path'
    
    for filename in glob.glob(os.path.join(folder_path, '*.csv')):
        with open(filename, 'r') as f:
            for line in f:
                print(line)