-2

Possible Duplicate:
How to search and replace text from one file to another using Python?

I have file1.txt :

<echo http://photobucket.com/98a267d32b056fb0a5c8c07dd4c35cc5.jpg ?>


http://lincoln.com/view/filename1.jpg

http://lincoln.com/banner1/filename2.jpg

http://lincoln.com/banner1/filename3.jpg

And I have file2.txt:

http://lincoln.com/banner2/filename1.jpg

http://lincoln.com/banner2/filename2.jpg

i want :

if filename exists in file1 but not in file2:

      remove line have filename

else if filename exists in file1 and in file2:

      the version in file2 replaces the line in file1

else if filename exists in file2 but not in file1:

      do nothing

every help me code it ! Thanks!


i tried this code: Can you help me edit my code !

def file_merge(file1,file2):
    file1contents = list()
    file2contents = list()
    file1=open('file1.txt','r')
    for line in file1:
        line= line.replace('\n','')
        line= line.split('/')

        file1contents.append(line)
    file1.close()
    file2=open('file2.txt','r')
    for line in file2:
        line = line.replace('\n','')
        line = line.split('/')
        file2contents.append(line)
    file2.close()
    file3contents=file1contents

    for x in file2contents:
        for y in file1contents:
            if x[-1] == y[-1] and x[2]==y[2]:
                file3contents[file3contents.index(y)]=x

           here I want code :if filename exists in file1 but not in file2:
                             remove line have filename in file 1





    file3 = open('out.txt','w')
    for line in file3contents:

        file3.write(str('/'.join(line))+'\n')

    file3.close()

file_merge('file1.txt','file2.txt')
2
  • remove line have filename from where ? from both files ? only from file1 ? Commented Dec 17, 2011 at 16:32
  • remove line have filename in file1 ! Thanks Commented Dec 17, 2011 at 17:03

1 Answer 1

1

This works given your urls are of the type 'http' as in your example.

import os
base = os.path.basename

f2_lines = [line.strip() for line in open("file2.txt")]

mylines = []
with open("file1.txt") as f:
    for line in f:
        line = line.strip()
        if not line.startswith('http'):
            mylines.append(line)
            continue
        filepath = base(line) 
        for f2_line in f2_lines:
            if filepath == base(f2_line):
                mylines.append(f2_line)
                break

with open("file3.txt", 'w') as f:
    f.write('\n'.join(mylines))

if you do not want a third file3 created just use file1.txt and it will be overwritten.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.