Pathlib路径拼接报错与WindowsPath JSON序列化问题求助
咱们一步步来解决你碰到的这两个问题:
1. 搞定TypeError: unsupported operand type(s) for +: 'WindowsPath' and 'str'
这个错误的问题出在你混合用了pathlib.Path的/路径拼接符和字符串的+号。root / 'Backups'返回的是一个WindowsPath对象,你直接把它和字符串email相加,Python可不认这种跨类型操作。
正确的做法是全程用Pathlib的/来拼接所有路径片段——这本来就是Pathlib设计的初衷,能帮你自动处理不同系统的路径分隔符,还避免类型问题:
dst = root / 'Backups' / email
这样三个部分会被正确拼成一个合法的WindowsPath对象,再也不会报错啦。
顺便提一嘴,你Move函数里写的root /'Backup/'+email+'/'其实也有同样的隐患,建议改成:
source_dir = root / 'Backup' / email
完全不用手动加斜杠,Pathlib会帮你搞定一切。
2. 解决TypeError: Object of type WindowsPath is not JSON serializable
Chrome的偏好设置字典(prefs)只认字符串类型的路径,但你传进去的dst是个WindowsPath对象,JSON没办法直接序列化这种对象。
解决起来超简单,把Path对象转成字符串就行:
prefs = {"download.default_directory": str(dst)}
要是你希望路径用正斜杠(有些场景下兼容性更好),也可以用dst.as_posix():
prefs = {"download.default_directory": dst.as_posix()}
修改后的完整代码
from pathlib import Path import glob import os import shutil root = Path(__file__).parent def myfunction(self, email): # 用Pathlib的/拼接所有路径部分 dst = root / 'Backups' / email Path(dst).mkdir(parents=True, exist_ok=True) # 把Path对象转为字符串传给Chrome的偏好设置 prefs = {"download.default_directory": str(dst)} def Move(self, email): # 规范路径拼接方式,避免混合+和/ source_dir = root / 'Backup' / email dst = root / 'BackUpZip' / email Path(dst).mkdir(parents=True, exist_ok=True) # 这里也可以用Path对象处理,不用手动加斜杠 files = glob.iglob(os.path.join(str(source_dir), "*.zip")) for file in files: if os.path.isfile(file): shutil.copy(file, str(dst)) os.remove(file)
内容的提问来源于stack exchange,提问作者Lewis Green
相关产品推荐
相关产品推荐

