Facebook Twitter Instagram
    TecAdmin
    • Home
    • FeedBack
    • Submit Article
    • About Us
    Facebook Twitter Instagram
    TecAdmin
    You are at:Home»General Articles»How to Count Number of Lines in File with Python

    How to Count Number of Lines in File with Python

    By RahulJune 16, 20191 Min ReadUpdated:September 16, 2019

    This is a small Python script to count the number of lines in a text file. To run this script you must have Python installed on your system. Now save below script in a Python script (eg: count.py) and update test.txt with your filename in the script to which you need to count lines.

    Advertisement
    vim count.py
    

    1
    2
    3
    4
    5
    6
    fname = "test.txt"
    count = 0
    with open(fname, 'r') as f:
        for line in f:
            count += 1
    print("Total number of lines is:", count)

    Then execute the script on the command line and see the result. This will show you the number of lines available in a file.

    python3 count.py
    
    Total number of lines is: 513
    

    Python
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email WhatsApp

    Related Posts

    Error: EACCES: permission denied, scandir (Resolved)

    How To Install Python 3.11 on Ubuntu 22.04 / 20.04

    How to Install Python 3.11 on Amazon Linux 2

    View 1 Comment

    1 Comment

    1. NUR IZYANI on December 4, 2020 2:11 pm

      hello, I’m from malaysia.
      i’m doing my python exercise using Pycharm.
      can you help me solve this coding?

      def main(name, number):
      try:
      name[number] = name[number] + 1
      except KeyError as e:
      name[number] = 1
      return

      if __name__ == ‘__main__’:
      a_dictionary = {}
      pl = open(‘phonelist.txt’, ‘r’)
      for data in pl:
      main(name, number)
      for name, number in a_dictionary.items():
      print(name + ” – ” + number + ” : ” + str(number) + ” times”)

      *phonelist.txt*
      abu 0124512123
      azman 0137894561
      azman 0137894561
      ali 0194022433
      abu 0124512123
      azman 0137894561
      James 0194789632

      ***this is simple exercise to count the duplicate line in .txt files

      Reply

    Leave A Reply Cancel Reply

    Advertisement
    Recent Posts
    • Error: EACCES: permission denied, scandir (Resolved)
    • How To Install Python 3.11 on Ubuntu 22.04 / 20.04
    • How to Install Python 3.11 on Amazon Linux 2
    • An Introduction to the “./configure” Command: Compiling Source Code in Linux
    • How to Install PHP 8.x on Pop!_OS
    Facebook Twitter Instagram Pinterest
    © 2023 Tecadmin.net. All Rights Reserved | Terms  | Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.