0

Hi everyone
I'm new to python and programming in general and wonder if anyone would be able to help me...
I am trying to open a text file, search for a certain value (1585 in this case), and then write all of the lines containing this value to a new text file.

I have encosed the code I have been trying to write but this just seems to write each line to the text file, which is then overwritten by the next line. Do you have any ideas? Any help would be greatly appreciated!

a = open(r'F:\tester.txt').xreadlines()
for line in a:
	if (line.find('1585')!=-1):
		isolated_lines = line
				
file = open('F:\write_it.txt', 'w')
file.write(str(isolated_lines))
file.close
2
Contributors
2
Replies
3
Views
8 Years
Discussion Span
Last Post by perksieuk
0

That's because on each loop you overwrote isolated_lines. maybe you meant isolated_lines += line . However, here is my interpretation of your code:

source = open("F:\\tester.txt")
dest = open('F:\\write_it.txt', 'w')
for line in source.readlines():
    if "1585" in line:
        dest.write(line)
source.close()
dest.close()

I like it better 'cause it's more pythonic (more concise, easier to read)

0

That's fantastic!
Thankyou very much for taking the time to help me out

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.