【问题标题】:Error opening file - Python 3.3 [duplicate]打开文件时出错 - Python 3.3 [重复]
【发布时间】:2013-01-26 19:22:43
【问题描述】:

可能重复:
IOError when trying to open existing files

我在 python 3.3 中使用 open() 打开文件时遇到问题,知道为什么吗?
我在努力

import os

filelist = [ f for f in os.listdir( os.curdir )]
singleFile = filelist[a]
hppfile = open(singleFile, 'r')

我明白了

FileNotFoundError: [Errno 2] No such file or directory: '-file that is actually inside the directory-'

想法?
在 Windows 上,我刚开始学习这个以编写一些快速脚本

【问题讨论】:

  • os.listdir() 返回文件名,而不是完整路径。
  • os.listdir() 已经返回一个列表,并且默认参数已经是 os.curdir btw。但是我无法用当前目录中的文件重现这个问题,所以我怀疑你的代码示例与你的真实代码不匹配。
  • @MartijnPieters Full code - 它只有几行,所以我不确定它可能有什么问题,真的

标签: python file python-3.x


【解决方案1】:

如果您阅读documentation for listdir,您会看到它返回的是文件名而不是完整路径。

你需要类似的东西

current_dir_path = os.getcwd()
open(os.path.join(curren_dir_path, file), 'r')

【讨论】:

  • 我已经在评论中说明了这一点,但 OP 列出了 当前目录
  • 那么在python中你需要完整的路径来打开一个文件吗?我认为它可能是默认的 C++ 中的相对路径
  • @P.K.:相对路径应该可以正常工作。
  • 哦,很好,成功了,没有错误,谢谢!
猜你喜欢
  • 2020-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-20
  • 2017-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多