【问题标题】:os.path.exists returns False, but os.path.abspath returns the pathos.path.exists 返回 False,但 os.path.abspath 返回路径
【发布时间】:2021-06-15 10:32:30
【问题描述】:

此代码应从 xlsx 文件中提取图片并保存副本并在新目录中重命名 3 次。 os.mkdir 在桌面上创建目录并保存第一张图片,但之后我得到

    os.rename(filename, new_name)
FileNotFoundError: [WinError 2] Impossible  to find the specified file: 'image1.jpeg' -> 'newPicone0.jpeg

当我检查目录的绝对路径时,我得到了这个 os.path.abspath('renamedPix') 'C:\\Users\\divel\\Desktop\\XLSpix\\renamedPix' 即使该目录不在XLSpix文件夹中而是在桌面上。

检查目录的存在我得到这个: os.path.exists('renamedPix') False

我不明白是什么导致了问题。 完整代码如下:

from zipfile import ZipFile
import re
import os
import shutil

file_name= "fote.xlsx"
directory= "renamedPix"
parent_dir = "C:\\Users\\divel\\Desktop"
path = os.path.join(parent_dir, directory)
os.mkdir(path)

with ZipFile(file_name, 'r') as zipObj:
     counter = 0
     
     for file in zipObj.infolist():
         name = file.filename
         match = re.findall("jpeg$", name)
         
         if match:
            filename = os.path.basename(file.filename)
            
            for i in range(3):
                source = zipObj.open(file)
                target = open(os.path.join(path, filename), 'wb')
                
                with source, target :
                    shutil.copyfileobj(source, target)
                pic_names = ['one', 'two', 'three']
                new_name = 'newPic'+pic_names[i]+str(counter)+'.jpeg'
                os.rename(filename, new_name)
            counter += 1

感谢您的帮助。

【问题讨论】:

  • 你为什么用ZipFile打开一个.xlsx文件?
  • @astrochun 所有以“x”结尾的办公文件(docx、pptx、xlsx 等)实际上都是 zip 文件
  • 啊。鉴于您正在尝试从特定文件中提取图像,我们确实需要一个最小的可重现 XLSX 来测试您的代码。
  • 你从os.path.exists('C:\\Users\\divel\\Desktop\\XLSpix\\renamedPix')得到什么?
  • @YashvanderBarnel 我猜错了。

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


【解决方案1】:

将我的评论变成答案:问题在于 os.rename() 的参数只是文件名,而不是路径名。因此,操作系统试图重命名当前工作目录中的文件(它们不存在)。传递完整路径名来重命名解决了这个问题:

os.rename(os.path.join(path, filename), os.path.join(path, newname))

【讨论】:

  • 你现在让事情变得更清楚了。再次感谢您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-05
  • 1970-01-01
相关资源
最近更新 更多