0

New to programming here and was wondering if anyone could help me out:

I'm trying to print or return the number of lines found in the below code using one line and I can't figure it out.

query = raw_input("Enter string to search for: ")
for line in open("list2.csv"):
    if query in line:
        print line,
miradulo
  • 28,857
  • 6
  • 80
  • 93
Exempt
  • 15
  • 1
  • You will have to read the whole file anyway but you can do it in a single line using a list comprehension. See my answer. – trans1st0r Apr 13 '16 at 15:24

4 Answers4

0

Use a list comprehension like this:

with open("list2.csv") as f:
 print(sum(query in line for line in f))  #gives number of lines found 
trans1st0r
  • 2,023
  • 2
  • 17
  • 23
  • Thanks! exactly what I was looking for. – Exempt Apr 13 '16 at 15:27
  • 1
    Just a suggestion: use a genexp in place if the list comp. `sum(query in line for line in f)`. There is no need for the intermediate list of `bool` – C Panda Apr 13 '16 at 15:34
0

There have been identical questions asked on here:

How to get line count cheaply in Python?

Here is the method that thread provides:

def file_len(fname):
with open(fname) as f:
    for i, l in enumerate(f):
        pass
return i + 1

Search is your friend :).

Community
  • 1
  • 1
Daniel Flannery
  • 1,166
  • 8
  • 23
  • 51
0

I would suggest for clarity that you avoid using just a single line! Here is something that should work:

query = raw_input("Enter string to search for: ")
lines = []
for line in open("list2.csv"):
    if query in line:
        lines.append(line)
        print line,
print "Number of lines:", len(lines)

If you really wanted a single line, you could do the following:

query = raw_input("Enter string to search for: ")
print "Number of lines:", len([line for line in open("list2.csv") if query in line])
alexoneill
  • 503
  • 3
  • 13
0

Not sure if this would be the best option, but it's the easiest.

Add a counter to your if statement to increase by one for every time the if statement executes.

Try this:

counter = 0
query = raw_input("Enter string to search for: ")
for line in open("list2.csv"):
    if query in line:
        print line
        counter += 1
return counter
Levi Muniz
  • 389
  • 3
  • 16