如何使用关键字通过Python替换和附加文件文本中的URL?

时间:2011-12-17 14:56:15

标签: python url replace append

  

可能重复:
  How to search and replace text from one file to another using Python?

我有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

我有file2.txt

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

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

我想:

如果文件名存在于file1中但不存在于file2中:

      remove line have filename

否则如果文件名存在于file1和file2中:

      the version in file2 replaces the line in file1

否则如果文件名存在于file2中但不存在于file1中:

      do nothing

每个人都帮我编码吧!谢谢!


我试过这段代码: 你能帮我编辑我的代码吗?

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')

1 个答案:

答案 0 :(得分:1)

如果您的网址类型为“http”,则可以使用此功能。

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))

如果您不想创建第三个文件3,只需使用file1.txt,它将被覆盖。