os.rename 和os.replace
阿新 • • 發佈:2019-01-20
命名 spa style else put pen lac pre txt
1 f1 = open("hello.txt","w") 2 f1.write("hello,my name is bobo.") 3 f1.close() 4 def func(): 5 name = input("輸入名字:") 6 content = input("輸入內容:") 7 new_content = input("輸入文件新內容:") 8 new_name = name + ".new" 9 import os 10 f = open(name,"r") 11 f_new = open(new_name,"w") 12 for line in f: 13 if content in line: 14 new_line = line.replace(content,new_content) 15 else: 16 new_line = line 17 f_new.write(new_line) 18 f.close() 19 f_new.close() 20 os.replace(new_name,name) # 替換replace不會報錯 21 func() #rename 重命名name是目錄裏已存在的文件, 則會報錯
os.rename 和os.replace