V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
piaochen0
V2EX  ›  Python

被 Python 的文件复制给搞混乱了...

  •  
  •   piaochen0 · 2018-01-19 23:12:15 +08:00 · 2703 次点击
    这是一个创建于 2260 天前的主题,其中的信息可能已经有所发展或是发生改变。

    之前写的一个模块,运行一点问题都没有,今天某次打开以后,莫名其妙报错
    进去看了下,原来是文件复制这这块出了问题
    代码意图是将当前文件夹下的 screenshot.png 复制到 backup 目录中,并且命名加时间。 代码为:
    orifilename = './screenshot.png'
    destfilename = "./backup/screenshot_{0}.png".format(datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')) shutil.copyfile(orifilename, destfilename)

    现在是 shutil.copyfile 这个报错,报 destfilename 文件不存在...
    FileNotFoundError: [Errno 2] No such file or directory: './backup/screenshot_2018_01_19_22_44_07.png'

    也看了源代码,
    with open(src, 'rb') as fsrc:
    with open(dst, 'wb') as fdst:
    copyfileobj(fsrc, fdst)

    源代码里主要是这里第二行报错,
    复制文件,必须要源文件存在,为什么会是这样设计...
    而且更诡异的是,之前运行一直良好,目标文件夹一直都有备份的文件。就今天才会报错...
    我已经混乱了....
    可能这个问题比较 Low,但是大家还是帮我看看吧...

    6 条回复    2018-01-20 11:29:37 +08:00
    biggray0312
        1
    biggray0312  
       2018-01-19 23:26:38 +08:00
    ./backup 这个文件夹是不是不存在
    ipwx
        2
    ipwx  
       2018-01-20 00:09:22 +08:00
    if not os.path.exists(os.path.split(dst)[0]): os.makedirs(os.path.split(dst)[0])
    eaglexiang
        3
    eaglexiang  
       2018-01-20 00:55:31 +08:00
    1. 确认"backup"文件夹是否存在;
    2. 确认代码运行的当前目录“./”是否正确。
    piaochen0
        4
    piaochen0  
    OP
       2018-01-20 11:10:42 +08:00
    @eaglexiang 刚一步一步调试且观察了文件夹,另外一个同事写的删除备份文件夹的程序被提前调用...导致我这边 backup 文件夹被删了。一直以为这个 backup 文件夹铁定在的。文件夹就被新建了一次...
    wizardoz
        5
    wizardoz  
       2018-01-20 11:20:34 +08:00
    这个锅 python 不背,操作系统的锅,顶多是 shutil 的锅
    piaochen0
        6
    piaochen0  
    OP
       2018-01-20 11:29:37 +08:00
    @wizardoz 是我自己程序的问题,昨晚被这个 bug 搞懵逼了,谢谢大家。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   980 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 20:30 · PVG 04:30 · LAX 13:30 · JFK 16:30
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.