Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
4 views
in Python by (50.2k points)

I am having an example.csv with the below contents:

1, "A towel,",1.0

42," it says, ",2.0

1337, is about the most,-1

0, massively useful thing,123

-2, an interstellar hitchhiker can have.,3

How can I import this example.csv with Python?

Likewise, if I have:

data = [(1, "A towel,", 1.0),

        (42, " it says, ", 2.0),

        (1337, "is about the most ", -1),

        (0, "massively useful thing ", 123),

        (-2, "an interstellar hitchhiker can have.", 3)]

In the above-given data, how is it possible to write to a CSV file using Python?

1 Answer

0 votes
by (107k points)

Kindly refer to the below code that will import the CSV files and it will write CSV files with Python.

Python 3: Reading a CSV file

Pure Python

import csv

# Define data

data = [

    (1, "A towel,", 1.0),

    (42, " it says, ", 2.0),

    (1337, "is about the most ", -1),

    (0, "massively useful thing ", 123),

    (-2, "an interstellar hitchhiker can have.", 3),

]

# Write CSV file

with open("test.csv", "wt") as fp:

    writer = csv.writer(fp, delimiter=",")

    # writer.writerow(["your", "header", "foo"])  # write header

    writer.writerows(data)

# Read CSV file

with open("test.csv") as fp:

    reader = csv.reader(fp, delimiter=",", quotechar='"')

    # next(reader, None)  # skip the headers

    data_read = [row for row in reader]

print(data_read)

#After this, the contents of data_read are:

[['1', 'A towel,', '1.0'],

 ['42', ' it says, ', '2.0'],

 ['1337', 'is about the most ', '-1'],

 ['0', 'massively useful thing ', '123'],

 ['-2', 'an interstellar hitchhiker can have.', '3']]

Please be informed that the CSV reads only strings. You need to convert to the column data types manually. 

For more details on the same, you can refer to the Python online course. It will help you gain more knowledge. 

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...