You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python备份脚本用%H:%M:%S格式报OSError: [Errno 22]错误求助

问题:Python备份脚本使用冒号作为时间分隔符时出现OSError错误

编写Python备份脚本时,使用%H:%M:%S格式生成时间戳作为文件名一部分时,触发OSError: [Errno 22] Invalid argument错误;但将时间分隔符改为点(.)时一切正常。想请教该错误的原因,以及如何正确使用冒号作为时间分隔符?

脚本代码

import os, time, zipfile

source = ["C:\Users\Daniel\Documents\Projects", "C:\Users\Daniel\Pictures\pics"]
target_dir = 'D:\Backup'

today = target_dir + os.sep + time.strftime('%Y.%m.%d')

comment = input('Enter a comment: ')
com = comment.replace(' ', '_') + '.zip'

now = time.strftime('%Y.%m.%d. %H:%M:%S')

if not os.path.exists(today):
    os.mkdir(today)
    print('Folder made successfully')

if len(comment) == 0: 
    target = today + os.sep + now + '.zip'

else: 
    target = today + os.sep + now + '_' + com 

z = zipfile.ZipFile(target, 'w' )

def zip(c):
    for a in c:
        for folder, subfolder, files in os.walk(a):
            for file in files:
                z.write(os.path.join(folder, file))
         
zip(source)

z.close()

错误回溯

Traceback (most recent call last):
  File "c:\Users\Daniel\Documents\Programming\backupscript.py", line 38, in <module>
    z = zipfile.ZipFile(target, 'w' )
  File "C:\Users\Daniel\AppData\Local\Programs\Python\Python310\lib\zipfile.py", line 1249, in __init__
    self.fp = io.open(file, filemode)
OSError: [Errno 22] Invalid argument: 'D:\Backup\2022.11.04\2022.11.04. 16:59:39_wa_w.zip'

错误原因

核心原因是Windows系统的文件名规则禁止使用半角冒号(:)。在Windows中,冒号是用来区分盘符与路径的特殊字符(比如C:\),系统会将文件名中的冒号判定为非法字符,因此创建带冒号的文件时会抛出无效参数的OSError。而Linux/macOS系统允许文件名包含冒号,所以这个问题仅会在Windows环境下出现。

解决方法

方法1:改用Windows允许的分隔符(推荐)

直接将时间格式化字符串中的冒号替换为点、横杠等合法字符,兼容性最好,不会出现跨平台问题。

修改代码中生成时间戳的行:

# 用点分隔时分秒
now = time.strftime('%Y.%m.%d. %H.%M.%S')
# 或者用横杠分隔
# now = time.strftime('%Y.%m.%d. %H-%M-%S')

方法2:使用全角冒号替代半角冒号

如果一定要保留冒号的视觉样式,可以使用Unicode全角冒号(:)代替半角冒号(:),Windows系统会将全角冒号视为普通字符,不会判定为非法。

修改代码:

now = time.strftime('%Y.%m.%d. %H:%M:%S')  # 注意这里是全角冒号

内容的提问来源于stack exchange,提问作者Daniel_Dzen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 16:05:34