所以,我用它來替換文件中的文本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"))
我該如何寫出來?
使用os.rename一次您保存 –
他想,如果我理解正確 – jmercouris
@jmercouris是該文件的兩個副本修改文件!請參閱我的編輯「試用版」 – maximusdooku