0

I can open two files at once using with open, now if i am going through two directories using this same method,

f = open(os.path.join('./directory/', filename1), "r") 
f2 = open(os.path.join('./directory2/', filename1) "r")

with open(file1, 'a') as x: 
   for line in f:
     if "strin" in line:
          x.write(line) 
with open(file2, 'a') as y:
   for line in f1:
      if "string" in line:
          y.write(line)

merge these into one method

7
  • what do you want to merge, the two files into one? Commented Nov 13, 2014 at 1:04
  • no, what I am doing is opening two different files in two different directories, looking for the same strings though and editing them, the only difference is that they are in different directories @smushi Commented Nov 13, 2014 at 1:06
  • what exactly is your question? Commented Nov 13, 2014 at 1:07
  • so your saying that the two files do no open? Commented Nov 13, 2014 at 1:08
  • 1
    If you're just trying to be less redundant, you could just wrap it around a function that takes a directory that you want to work with as a parameter. That would reduce repeated uses of code. Commented Nov 13, 2014 at 1:32

1 Answer 1

1

Your pseudocode (for line in f and f1, x.write(line in f) y.write(line in f1)) has the same effect as the original code you posted, and isn't useful unless there is something about the corresponding lines in the two files that you want to process.

But you can use zip to combine iterables to get what you want

import itertools

with open(os.path.join('./directory', filename1)) as r1, \
     open(os.path.join('./directory2', filename1)) as r2, \
     open(file1, 'a') as x, \
     open(file2, 'a') as y:
     for r1_line, r2_line in itertools.izip_longest(r1, r2):
         if r1_line and "string" in line:
             x.write(r1_line) 
         if r2_line and "string" in line:
             y.write(r1_line) 
  • I put all of the file objects in a single with clause using \ to escape the new line so that python sees it as a single line

  • The various permutations of zip combine iterables into a sequence of tuples.

  • I chose izip_longest because it will continue to emit lines from both files, using None for the files that empty first, until all lines are consumed. if r1_line ... just makes sure we aren't at the Nones for file that has been fully consumed.

  • This is a strange way to do things - for the example you've given, it's not the better choice.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.