how to count the total number of lines in a text file using python

前端 未结 11 1772
你的背包
你的背包 2020-12-01 04:44

For example if my text file is:

blue
green
yellow
black

Here there are four lines and now I want to get the result as four. How can I do th

相关标签:
11条回答
  • 2020-12-01 04:59

    You can use sum() with a generator expression here. The generator expression will be [1, 1, ...] up to the length of the file. Then we call sum() to add them all together, to get the total count.

    with open('text.txt') as myfile:
        count = sum(1 for line in myfile)
    

    It seems by what you have tried that you don't want to include empty lines. You can then do:

    with open('text.txt') as myfile:
        count = sum(1 for line in myfile if line.rstrip('\n'))
    
    0 讨论(0)
  • 2020-12-01 05:00
    count=0
    with open ('filename.txt','rb') as f:
        for line in f:
            count+=1
    
    print count
    
    0 讨论(0)
  • 2020-12-01 05:03

    For the people saying to use with open ("filename.txt","r") as f you can do anyname = open("filename.txt","r")

    def main():
    
        file = open("infile.txt",'r')
        count = 0
        for line in file:
                count+=1
    
        print (count)
    
    main ()
    
    0 讨论(0)
  • 2020-12-01 05:04

    One liner:

    total_line_count = sum(1 for line in open("filename.txt"))
    
    print(total_line_count)
    
    0 讨论(0)
  • 2020-12-01 05:04

    here is how you can do it through list comprehension, but this will waste a little bit of your computer's memory as line.strip() has been called twice.

         with open('textfile.txt') as file:
    lines =[
                line.strip()
                for line in file
                 if line.strip() != '']
    print("number of lines =  {}".format(len(lines)))
    
    0 讨论(0)
  • 2020-12-01 05:07

    Use:

    num_lines = sum(1 for line in open('data.txt'))
    print(num_lines)
    

    That will work.

    0 讨论(0)
提交回复
热议问题