2

This is a noob question, but without using Pandas (pd.read) how can I import a CSV file and load it to a DataFrame object so I can call it (e.g. print (loaded_file) ) and print the contents of the file in Python (2.7)?

Ali
  • 837
  • 2
  • 12
  • 18

3 Answers3

2
import pandas as pd
data = pd.read_csv('file_name')
Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
Hackaholic
  • 19,069
  • 5
  • 54
  • 72
2

unicodecsv library can also be used to read .csv files.

import unicodecsv
import pandas as pd

def read_csv(data):
""" Returns a list of dicts from .csv file passed in as data"""
    with open(data, "rb") as f:
        reader = list(unicodecsv.DictReader(f))
        return reader

file = read_csv('filename.csv') # call the function and pass in your 'filename'

pd.DataFrame(file) # call pd.DataFrame() function with file as an argument 
                   # to convert it to DataFrame object
Mr.Pacman
  • 350
  • 2
  • 7
1

Just read each line and split, also notice that you will need to know hoy to parse the types, for example:

def getCSV(filePath, sep=";"):
    with open(filePath, "r") as f:
        return [l.split(sep) for l in f]

then just load it into a pandas dataframe:

import pandas as pd
csvdata = getCSV("/da/real/path/file.csv")
pd.DataFrame(csvdata)
Netwave
  • 40,134
  • 6
  • 50
  • 93