2017-09-05 35 views
0

所以,我用它來替換文件中的文本odirx,然後將它寫出到另一個文件。但我希望輸出文件名爲sm_0120.txt而不是sm_template2.txt如何在不讀取整個文件的情況下更改輸出文件名?

replacements = {'odirx':'0120'} 

with open('/dir/sm_template.txt') as infile, open('/dir/sm_template2.txt', 'w') as outfile: 
    for line in infile: 
     for src, target in replacements.items(): 
      line = line.replace(src, target) 
     outfile.write(line) 

我該怎麼做?

閱讀後可以寫出來的整個文件,但我想這樣做沒有讀取整個文件

相關: replacing text in a file with Python

TRIAL

我是OKAY閱讀它如果這是我唯一的選擇

replacements = {'odirx':'0120'} 

with open('/dir/sm_template.txt') as infile, open('/dir/sm_template2.txt', 'w') as outfile: 
     for line in infile: 
      for src, target in replacements.items(): 
       line = line.replace(src, target) 
      lines.append(line) 
      outfile = os.path.join(os.path.normpath(os.getcwd()+os.sep+"sm_"+os.sep+target+os.extsep+"txt")) 

我該如何寫出來?

+0

使用os.rename一次您保存 –

+0

他想,如果我理解正確 – jmercouris

+0

@jmercouris是該文件的兩個副本修改文件!請參閱我的編輯「試用版」 – maximusdooku

回答

0

使用os.rename:

os.rename('/dir/sm_template2.txt', '/dir/sm_0120.txt') 
相關問題