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

前端 未结 11 1829
你的背包
你的背包 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 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)))
    

提交回复
热议问题