Python写入文件触发FileNotFoundError错误,寻求解决方案
解决Python写入文件时的FileNotFoundError及代码错误
核心错误原因
你遇到的FileNotFoundError是因为打开文件时未指定写入模式:Python中open()函数默认使用只读模式('r'),如果目标文件不存在,就会触发这个错误。要写入文件,必须指定写入模式,比如'w'(创建新文件或覆盖已有文件)或'a'(追加内容到文件末尾)。
代码里的其他问题
除了模式问题,你的代码还有几个明显错误:
- 错误调用了不存在的文件方法
w(),正确的写入方法是write() - 无意义的赋值语句
outfile = Bayofagbenro.r完全无效,应该删除 - 关闭文件时没有调用方法,
outfile.close要改成outfile.close()(必须加括号执行方法) - 手动管理文件关闭容易遗漏,推荐用
with语句自动处理文件的打开和关闭
修正后的代码
def main(): # 使用'w'模式打开文件,不存在则创建,存在则覆盖 with open('Bayofagbenro.txt', 'w') as outfile: outfile.write('Modupeola\n') outfile.write('Ayobami\n') outfile.write('AKintola\n') outfile.write('Omonike\n') outfile.write('Fehintoluwa\n') outfile.write('Modupeola is 44yrs, Ayobami is 42 years, AKintola is 38 years, omonike is 36 years while fehintoluwa is 30 years') if __name__ == "__main__": main()
效果说明
运行修正后的代码后,会自动创建Bayofagbenro.txt文件,内容完全符合你期望的输出格式。
内容的提问来源于stack exchange,提问作者Akintola
相关产品推荐
相关产品推荐

