[英]How do I put lines into a list from CSV using python
I am new to Python (coming from PHP background) and I have a hard time figuring out how do I put each line of CSV into a list. 我是Python的新手(来自PHP背景),我很难弄清如何将CSV的每一行都放入列表中。 I wrote this:
我这样写:
import csv
data=[]
reader = csv.reader(open("file.csv", "r"), delimiter=',')
for line in reader:
if "DEFAULT" not in line:
data+=line
print(data)
But when I print out data, I see that it's treated as one string. 但是当我打印出数据时,我看到它被视为一个字符串。 I want a list.
我想要一张清单。 I want to be able to loop and append every line that does not have "DEFAULT" in a given line.
我希望能够循环并在给定行中附加没有“ DEFAULT”的每一行。 Then write to a new file.
然后写入一个新文件。
How about this? 这个怎么样?
import csv
reader = csv.reader(open("file.csv", "r"), delimiter=',')
print([line for line in reader if 'DEFAULT' not in line])
or if it's easier to understand: 还是更容易理解:
import csv
reader = csv.reader(open("file.csv", "r"), delimiter=',')
data = [line for line in reader if 'DEFAULT' not in line]
print(data)
and of course the ultimate one-liner: 当然还有最终的一线:
import csv
print([l for l in csv.reader(open("file.csv"), delimiter=',') if 'DEFAULT' not in l])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.