Python 将 csv 文件加载到列表中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35558053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 16:36:01  来源:igfitidea点击:

load csv file into list

pythonpython-2.7csv

提问by Leem.fin

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

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

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

我只分别尝试了写入listCSV的代码,它有效,CSV 文件内容以制表符分隔,其内容如下:

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?

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

采纳答案by k-nut

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

您没有关闭要写入的文件,因此读取找不到要读取的数据。您可以使用该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)

If you do that the reading works fine.

如果你这样做,阅读效果很好。

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