0

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. 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. Then write to a new file.

4

1 回答 1

1

这个怎么样?

import csv

reader = csv.reader(open("file.csv", "r"), delimiter=',')
print([line for line in reader if 'DEFAULT' not in line])

或者如果更容易理解:

import csv

reader = csv.reader(open("file.csv", "r"), delimiter=',')
data = [line for line in reader if 'DEFAULT' not in line]
print(data)

当然还有终极单线:

import csv
print([l for l in csv.reader(open("file.csv"), delimiter=',') if 'DEFAULT' not in l])
于 2013-09-12T16:37:19.190 回答