jeudi 28 novembre 2019

How do I import data from n number of csv files within a folder?

[PYTHON HELP]

Hello, I would like some help figuring out how to import data from n number of files within a folder. Just as an example, I am currently trying to import the data within the first 3 files from a folder containing 30 files, but so far I have only been able to isolate the first 3 files without actually reading the data. When I try to extract the actual data I get an error stating that the file/directory does not exist.

This is the chunk of code that simply prints the first 3 files which works fine, but once I try to add more code that will actually read the data within the files, that's when I run into errors.

import os, csv
fcm_path = ("my directory")
fcm_files = sorted(os.listdir(fcm_path)) 

def fcm():
    count = 0
    for file in (fcm_files):
        if count < 4:
            if file.endswith('.csv'):
                print ('file: ' + file)
        else:
            break
        count = count + 1 

OUTPUT:

file: 001.csv
file: 002.csv
file: 003.csv

Here I tried being more specific but then I get an error stating that the file doesn't exist

import os, csv
fcm_path = ("my directory")
fcm_files = sorted(os.listdir(fcm_path)) 


def fcm():
    count = 0
    for file in (fcm_files):
        if count < 4:
            if file.endswith('.csv'):
                print ('file: ' + file)
                with open(file, 'r') as csvfile:
                    data = csvfile.read
                    print(data)
        else:
            break
        count = count + 1 

OUTPUT:


 File "<ipython-input-158-1f4c11da5a68>", line 1, in <module>
    fcm()
 File "<ipython-input-157-b977510dbfcd>", line 8, in fcm
    with open(file, 'r') as csvfile:

FileNotFoundError: [Errno 2] No such file or directory: '001.csv'

Aucun commentaire:

Enregistrer un commentaire