file_data = '' str1 = '1' str2 = '2' with open(loginfofile, 'r+') as f: #打開文件,r+模式,讀取 for line in f: if str1 in line: line = line.replace(str1, 'n') #將str替換為n if str2 in line: line2 = line.replace(str2, 'n') file_data += line2 with open(logproducefile, 'w') as f: #以寫入方式打開文件w f.write(file_data)