-1

I have been searching for following Python solution to copy selectively lines from 1 txt file to another. I can copy the whole file, but with only a few lines I get an error.

My code:

    f = open(from_file, "r")
    g = open(to_file, "w")
    #copy = open(to_file, "w") # this instruction copies whole file
    rowcond2 = 'xxxx' # look for this string sequence in every line

    for line in f:
        if rowcond2 in f:
            copy.write(line,"w") in g # write every corresponding line to  destination

    f.close()
    # copy.close() # code receive error to close destination
    g.close()

So without the rowcond2, I can copy the whole file. Yet with the condition nothing is written to destination file.

Thank you for your help.

user1739581
  • 85
  • 2
  • 14

2 Answers2

0

Why not to put your condition inside the for loop?

for line in f:
    if condition:
        copy.write(line)
Gabor
  • 1,409
  • 1
  • 14
  • 24
  • This helps! My coding is still confused between the 2 files. With your suggestion, I have corrected code (see my 1st entry). – user1739581 Jan 15 '16 at 19:35
0

I have been able to solve this case searching on SO:

Using python to write specific lines from one file to another file

@Lukas Graf: thank you for your detailed step wise explanation.

Community
  • 1
  • 1
user1739581
  • 85
  • 2
  • 14