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

Recommended Answers

All 2 Replies

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)

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.