[英]Python - Read CSV as List of Strings
I have a CSV file with only one column.我有一个只有一列的 CSV 文件。 Each row has some words inside.每行里面都有一些单词。
Hello World1
Hello World2
Hello World3
Now I want to read this file as a list of strings, each row is an item inside the list.现在我想将此文件作为字符串列表读取,每一行都是列表中的一个项目。 Like this:像这样:
['Hello World1', 'Hello World2', 'Hello World3']
I have tried below code:我试过下面的代码:
with open("myFile.csv", newline="") as f:
reader = csv.reader(f)
data = list(reader)
But it gave me another square brackets inside for each element.但是它给了我每个元素里面的另一个方括号。 How can I remove it?我怎样才能删除它?
[['Hello World1'], ['Hello World2'], ['Hello World3']]
Solution:解决方案:
This should solve your use case:这应该可以解决您的用例:
with open('myFile.csv') as file:
data = file.read().splitlines()
INPUT DATA:输入数据:
Hello World1
Hello World2
Hello World3
OUTPUT:输出:
['Hello World1', 'Hello World2', 'Hello World3']
If it is a simple text file, you can simply do如果它是一个简单的文本文件,你可以简单地做
with open("myFile.csv") as f:
data=[line for line in f]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.