Python code to read lines from text file and display those lines of length more than 50
In this example, you will know how to read lines from text file and display those lines of length more than 50.
Logic and Explanation
For the above problem, we first have to open the text file in read mode in our python program. In my example, I am taking a text file name "content.txt" which is present in the same directory where this python file is present. So, I just written the name of file otherwise you have to write the complete path of the file to open the file. This is the code to open file in read mode.
f = open("content.txt","r")
Now, we will read the content of the file by iterating through the content of the file. Note that when we iterate through the file, we get the values as the lines of file. Now, we will check the length of line and by using if condition we will check whether it's length is greater than 50 or not. If it's length is greater than 50 then we will print that line.
for line in f:
l=len(line)
if l > 50:
print(line)
Source Code
f = open("content.txt","r")
for line in f:
l=len(line)
if l>50:
print(line)
If you like the content, share it in your social media platforms so that we can help the maximum. If you have any query then feel free to ask in the comments below.
Post a Comment
For any doubts feel free to ask in comments below.
Stay Connected to Us for more such Courses and Projects.