1010111100011
1010111100011

Reputation: 93

How to Create dataframe from existing CSV file in Python

I am trying to create dataframe object from an existing CSV file in python but I am facing problems. I tried to import CSV file into python but I do not know whether I succeeded or not.

    >>> import os
    >>> userhome = os.path.expanduser('~')
    >>> csvfile= userhome + r'\Desktop\train.csv'
    >>> with open(csvfile, "r") as f:

After I wrote these statements it did not do anything.

So the First problem - Did I import CSV file to python? And if I did not how do I import?

After that how can I display data from CSV file in python?

I installed pandas

Python IDE 3.6.3 Shell

enter image description here

Upvotes: 0

Views: 14324

Answers (2)

StoanyMak
StoanyMak

Reputation: 11

Incase anyone is interested in using the python csv package to open csv files.

import os, csv
some_path = os.path.expanduser('~')
csv_file = some_path + '\path_to_file_from_home_dir\file_name.csv'
# Now let's read the file
with open (csv_file,'r+') as csvfile:
    csv_reader = csv.reader(csvfile, delimiter=' ')
    # Confirm that the code works by printing contents of the file 
    for row in csv_reader:
        print(', '.join(row))

You can read more about the csv reader module

to get its full capability

Upvotes: 1

skrubber
skrubber

Reputation: 1105

Rather, use pandas to read the csv:

import pandas as pd
df = pd.read_csv(csvfile)

for additional options to read csv, refer to: pandas read csv

Upvotes: 0

Related Questions