首页 > 编程语言 > 详细

Python中的用open打开文件错误,FileNotFoundError: [Errno 2] No such file or directory:

时间:2020-02-28 19:53:23      阅读:274      评论:0      收藏:0      [点我收藏+]

学习python的文件处理,刚开始打开文件,代码如下

f = open(‘test_file.txt‘, ‘r‘, encoding=‘UTF-8‘)
RES = f.readlines()
print(‘读取的内容%s‘ % RES)
f.close()

这里运行报错FileNotFoundError: [Errno 2] No such file or directory: ‘test_file.txt‘
意思是没有这个文件?

后来发现是因为多了后缀
修改代码:把文件名的后缀去掉了
f = open(‘test_file‘, ‘r‘, encoding=‘UTF-8‘)
RES = f.readlines()
print(‘读取的内容%s‘ % RES)
f.close()

运行成功:结果如下
读取的内容[‘1.zyh\n‘, ‘2.1995\n‘, ‘3.gggg‘]

注意:要读取的文件与py当前编辑的文件在同一个文件夹下,就不用加路径,不是同一个文件夹就要在文件名前面加路径
f = open(‘D:/zyh_test/test_file‘, ‘r‘, encoding=‘UTF-8‘)
RES = f.readlines()
print(‘读取的内容%s‘ % RES)
f.close()

Python中的用open打开文件错误,FileNotFoundError: [Errno 2] No such file or directory:

原文:https://www.cnblogs.com/hongyufei/p/12378218.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!