Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

load csv file into list

I have a python script, it first writes a list to CSV file, after which immediately loads the CSV file into another list.

I tried separately only the code which writes list to CSV, it works, the CSV file content is tab delimited, its content is like:

car house wife

But when put all together:

import csv

// write list to CSV file, it works!
the_list=["car","house","wife"]
the_file = open("my_file.csv", 'w+')
writer = csv.writer(the_file, delimiter='\t')
writer.writerow(the_list)


// read CSV file & load into list
my_file = open("my_file.csv", 'r')
reader = csv.reader(my_file, delimiter='\t')
my_list = list(reader)
print(my_list)

I get an empty list printed out : [] , what is wrong?

like image 518
Leem.fin Avatar asked Mar 14 '23 05:03

Leem.fin


1 Answers

You are not closing the file that you are writing to so the reading finds no data to read. You can use the with statement to make sure that the file is closed.

import csv

# write list to CSV file, it works!
the_list=["car","house","wife"]
with open("my_file.csv", 'w') as outfile:
    writer = csv.writer(outfile, delimiter='\t')
    writer.writerow(the_list)


# read CSV file & load into list
with open("my_file.csv", 'r') as my_file:
    reader = csv.reader(my_file, delimiter='\t')
    my_list = list(reader)
    print(my_list)

If you do that the reading works fine.

➜  python test.py
[['car', 'house', 'wife']]
like image 190
k-nut Avatar answered Mar 19 '23 17:03

k-nut