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.

1
  • that works as well... should have put it in answer. :/ Commented Sep 17, 2013 at 21:40

1 Answer 1

1

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])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.