zoukankan      html  css  js  c++  java
  • Python中的用open打开文件错误,FileNotFoundError: [Errno 2] No such file or directory:

    学习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 ', '2.1995 ', '3.gggg']

    注意:要读取的文件与py当前编辑的文件在同一个文件夹下,就不用加路径,不是同一个文件夹就要在文件名前面加路径
    f = open('D:/zyh_test/test_file', 'r', encoding='UTF-8')
    RES = f.readlines()
    print('读取的内容%s' % RES)
    f.close()
  • 相关阅读:
    php
    图片拖拽
    12.20
    正则详细讲解
    12.19
    正则
    闭包
    date类
    二分查找
    冒泡排序
  • 原文地址:https://www.cnblogs.com/hongyufei/p/12378218.html
Copyright © 2011-2022 走看看