【问题标题】:Receiving "no such file or directory" error within a for loop - recognizes file initially在 for 循环中收到“没有这样的文件或目录”错误 - 最初识别文件
【发布时间】:2021-11-21 16:07:49
【问题描述】:

代码如下:

for WorkingFile in os.listdir(path):  
    print(WorkingFile)
    xlsx = pd.ExcelFile(WorkingFile)

返回这个:

ChetworthPark_Test.xlsx
FileNotFoundError: [Errno 2] No such file or directory: 'ChetworthPark_Test.xlsx'

所以它打印文件名(证明它识别路径),但之后不将它传递给变量“xlsx”。关于我哪里出错的任何想法?有关更多上下文,我正在 Google Colab 中运行它。

【问题讨论】:

  • 尝试将路径添加到您的文件名...

标签: python pandas dataframe google-colaboratory


【解决方案1】:

os.listdir 返回文件名而不是路径。所以你需要预先添加路径:

for fn in os.listdir(path):
   do_something(f"{path}/{fn}")

正如评论中指出的,/ 用于路径不是通用的,所以我们有os.path.join

from os.path import join
for fn in os.listdir(path):
    fn = join(path, fn) # handles / or \
    do_something(fn)

不过,现在我们已经有一段时间了 pathlib.Path,这让这变得更容易了:

from pathlib import Path
for fn in os.listdir(path):
    do_something(Path(path) / fn)

或者,更自然地使用 pathlib:

from pathlib import Path
for fn in Path("/path/to/look/at").expanduser().resolve().glob("*"):
    if not fn.is_file():
        continue
    do_something(fn)

(请注意,我还处理了诸如 ~/some-file 之类的扩展内容并在此处简化了路径)

【讨论】:

  • 如果 OP 使用的是 Windows,您可能希望使用 os.path.join 而不是硬编码正斜杠。
  • 公平点。会更新
  • 太棒了!效果很好。 TIL 关于字符串文字也是如此
  • @SRed2 优秀;如果可以解决问题,请随时接受。请注意,我真的会为所有事情使用 pathlib:弄乱字符串迟早会出错
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-03-28
  • 1970-01-01
  • 2021-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-24
相关资源
最近更新 更多