没有这样的目录文件'文件.xml'

2024-04-26 13:09:38 发布

您现在位置:Python中文网/ 问答频道 /正文

在使用python3中的zipfile模块创建zip文件时遇到了一个小问题。在

我有一个包含xml文件的目录,我希望从同一目录中的所有这些文件创建一个zip归档文件,但是一直遇到FileNotFoundError: [Errno 2] no such file or directory: 'file.xml'的错误

脚本:

import datetime
import os
import zipfile


path = '/Users/xxxx/reports/xxxx/monthly'
month = datetime.datetime.now().strftime('%G'+'-'+'%B')
zf = os.path.join(path, '{}.zip'.format(month))

z = zipfile.ZipFile(zf, 'w')
for i in os.listdir(path):
    if i.endswith('.xml'):
        z.write(i)
z.close()

似乎当调用z.write(i)时,它在工作目录中查找xml文件,但是工作目录是/Users/xxxx/scripts,python脚本就在这里。在

如果可能的话,如何让z.write(i)在不改变当前工作目录的情况下查看path变量。在


Tags: 文件pathimport目录脚本datetimeosxml
2条回答

What actually happens is that as you loop through os.listdir(path), the i itself is simply the FileName which does not include the real Path to the File. There are a couple of ways to get around this; the simplest (but crudest) of which is shown below:

import datetime
import os
import zipfile

path    = '/Users/xxxx/reports/xxxx/monthly'
month   = datetime.datetime.now().strftime('%G'+'-'+'%B')
zf      = os.path.join(path, '{}.zip'.format(month))
z       = zipfile.ZipFile(zf, 'w')

for i in os.listdir(path):
    # DECLARE A VARIABLE TO HOLD THE FULL PATH TO THE FILE:
    xmlFile = "{}/{}".format(path, i)   # <== PATH TO CURRENT FILE UNDER CURSOR
    if xmlFile.endswith('.xml'):
        z.write(xmlFile)
        z.write(filename=xmlFile, arcname="ARCHIVE_NAME_HERE", ) # <== CHANGE
z.close()  

希望这有帮助。
干杯祝你好运。。。在

使用os.chdir公司移动到文件路径并尝试将文件写入zip。在

import datetime
import os
import zipfile


path = '/Users/xxxx/reports/xxxx/monthly'
month = datetime.datetime.now().strftime('%G'+'-'+'%B')
zf = os.path.join(path, '{}.zip'.format(month))

z = zipfile.ZipFile(zf, 'w')
os.chdir(path)   #Change DIR
for i in os.listdir(path):
    if i.endswith('.xml'):
        z.write(i)
z.close()

不改变方向:

^{pr2}$

相关问题 更多 >