【问题标题】:Can't find file - FileNotFoundError: [Errno 2] No such file or directory找不到文件 - FileNotFoundError: [Errno 2] 没有这样的文件或目录
【发布时间】:2021-08-26 09:51:58
【问题描述】:

我的代码如下所示:

import os
from os import listdir
from os.path import isfile, join
import pyexcel as p

rootdir = r'C:/Users/aleks/Desktop/test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        if file.endswith('.xls'):
            new_file = p.save_book_as(file_name=file, dest_file_name=file.split('.')[0]+ '.xlsx')
            os.remove(file)
        else:
            continue

现在我知道这部分工作正常,因为它返回的正是我想要的:

rootdir = r'C:\Users\aleks\Desktop\test'

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        print(file)

使用print(file) 后文件已正确列出,但我无法将它们转换为 xlsx,因为出现错误:FileNotFoundError: [Errno 2] No such file or directory: 'file1.xls'。我觉得很奇怪,因为使用print(file) 后我可以清楚地看到文件

为了澄清,在 rootdir 中有包含 .xls 文件的目录,这些文件必须转换为 .xlsx

【问题讨论】:

  • 你试过用双反斜杠代替单反斜杠吗?
  • 是的,我有,不幸的是结果还是一样。

标签: python directory file-conversion file-not-found os.path


【解决方案1】:

试试下面的代码。我想问题是您尝试删除与您的 Python 根目录不同的 sub_directory 中的文件。

for root, dirs, files in os.walk(rootdir):
    for name in files:
        if name.endswith('.xls'):
            fname = os.path.join(root, name)
            new_file = p.save_book_as(file_name=fname, dest_file_name=os.path.join(root, fname.split('.')[0]+ '.xlsx'))
            os.remove(fname)

【讨论】:

  • 不幸的是它仍然给出同样的错误:FileNotFoundError: [Errno 2] No such file or directory
  • 哪一行给出了错误?我已经编辑了我的答案,你可以再试一次。
  • ----> 6 new_file = p.save_book_as(file_name=file, dest_file_name=file.split('.')[0]+ '.xlsx') 这行给出了一个错误,现在可以了,谢谢,您介意快速解释一下为什么我的代码不起作用吗?
  • 正如我在回答中所说,问题在于name 是位于 Python 根目录之外的文件。你需要使用绝对路径,这就是我使用os.path.join(root, fname)的原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-11-13
  • 2019-11-03
  • 2021-08-24
  • 2021-03-07
  • 2015-06-09
  • 2021-04-01
  • 2021-10-15
相关资源
最近更新 更多