Prerequisites: File Handling in Python
Counting the number of characters is important because almost all the text boxes that rely on user input have a certain limit on the number of characters that can be inserted. For example, the character limit on a Facebook post is 63, 206 characters. Whereas, for a tweet on Twitter the character limit is 140 characters and the character limit is 80 per post for Snapchat.
This program in Data file handling in Python emphasizes the counting the number of lines in a text file in Python.
- Open the file in read mode and assign a file object named “file”.
- Assign 0 to the counter variable.
- Read the content of the file using read function and assign it to a variable named “Content”.
- Create a list of the Content where the elements are split wherever they encounter an “\n”.
- Traverse the list using a for loop and iterate the Counter variable respectively.
- Further the value now present in the variable Counter is displayed which is the required action in this program.
Below is the implementation.
Let’s suppose the text file looks like this –
This is the number of lines in the file 4
- Python program to Count the Number of occurrences of a key-value pair in a text file
- Python - Get number of characters, words, spaces and lines in a file
- Python | Count occurrences of each word in given text file (Using dictionary)
- Python - Reading last N lines of a file
- Python program to copy odd lines of one file to other
- Convert Text and Text File to PDF using Python
- Extract text from PDF File using Python
- Python | Scramble words from a text file
- Saving Text, JSON, and CSV to a File in Python
- Convert Text file to JSON in Python
- Extract numbers from a text file and add them using Python
- Python program to extract Email-id from URL text file
- Python | Finding 'n' Character Words in a Text File
- Python program to Reverse a single line of a text file
- Python | Create an empty text file with current date as its name
- Python - Convert simple lines to bulleted lines using the Pyperclip module
- Python | Splitting Text and Number in string
- Count of lines required to write the given String
- Text Input box with a verification button in kivy (using .kv file)
- Python program to reverse the content of a file and store it in another file
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.