user123123123 user123123123 - 2 months ago 5
Python Question

Extract rows from txt file using python

How can i look for a string in a file row by row without using readlines().
if string found then write the line in another file.

Basically I am trying to extract rows that have a specific string in them.


If there are a varying number of lines to read, readline() is not recommended, once you'll have to check if the end of file was reached.

Using a simple for loop, you can get the result you want:

file = open('your_file.txt', 'r')

lines = [] # Initialize output array
for line in file: 
    if "YOUR STRING" in line:

# Here you will have all the "selected" lines in the lines array
# Now, you can write to the output file
out_file = open('output_file.txt', 'w')
for line in lines:

Hope it helps.