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?
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']]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With