将csv文件加载到列表中

时间:2016-02-22 15:54:38

标签: python python-2.7 csv

我有一个python脚本,它首先将list写入CSV文件,然后立即将CSV文件加载到另一个list

我只是单独尝试将list写入CSV的代码,它有效,CSV文件内容以制表符分隔,其内容如下:

car house wife

但是当把它们放在一起时:

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)

我打印出一个空列表:[],出了什么问题?

1 个答案:

答案 0 :(得分:6)

您没有关闭要写入的文件,因此读取时找不到要读取的数据。您可以使用with语句确保文件已关闭。

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)

如果你这样做,阅读工作正常。

➜  python test.py
[['car', 'house', 'wife']]