-1

In a directory, I have around 100 files- csv datas. How to import them to python? I searched and I found:

import csv
f = open("imgdata.csv")
r = csv.reader(f)
f.close()

but it is not working for a directory. It's not about looking for the files, it's about importing them.

mishakisha
  • 39
  • 1
  • 1
  • 7
  • See the examples in the documentation for reading the contents into Python. You will need another method to open multiple files one by one https://docs.python.org/2/library/csv.html – roganjosh Sep 21 '16 at 12:31

4 Answers4

1

Use glob:

import glob
import csv
for f_name in glob.glob("*.csv"):
    with open(f_name) as f:
        reader = csv.reader(f)
        # do stuff here
Chris_Rands
  • 38,994
  • 14
  • 83
  • 119
0

Try this Solution:

import os

directory = os.path.join("c:\\","path")
for root,dirs,files in os.walk(directory):
    for file in files:
       if file.endswith(".csv"):
           f=open(file, 'r')
               #  perform calculation
           f.close()
Dsenese1
  • 1,106
  • 10
  • 18
0

You can try:

import glob

for files in glob.glob("*.csv"):
    #to do --
Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61
0

That's a basis, what you're going to want to do is put that into a for loop going through all the filenames in the directory, like so:

import os
import csv
dirlist = os.scandir(DIRNAME)
for x in dirlist:
    f = open(str(x)+".csv")     
    r = csv.reader(f)
    f.close()