2011-12-17 5 views
-2

可能性の重複:
How to search and replace text from one file to another using Python?ファイルテキストのURLをPythonのKeywordで置き換えて追加するには?

私が持っている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に存在する場合:ファイル名がFILE2に存在する場合

 the version in file2 replaces the line in file1 

が、ファイル1に含まれていません:

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

'remove line have filename'どこから?両方のファイルから? file1からのみ? – joaquin

+0

行を削除するとfile1にファイル名があります!ありがとう – j3oy9x

答えて

1

これは、あなたのURLがあなたの例のように '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番目のファイル3を作成したくない場合は、file1.txtを使用するだけで上書きされます。

関連する問題