pythondecode函数 attributeerror_操作系统路径AttributeError:“str”对象没有属性“exists”...

一般的想法是使用python复制文件。虽然我可以用我的方法来解决这些错误,但我也希望了解在这种情况下我做错了什么。在import shutil

from os import path

def main(filename):

if path.exists(filename):

src = path.realpath(filename)

head, tail = path.split(src)

dst = src + ".bak"

shutil.copy(src,dst)

main('C:\\Users\\test.txt') #This raises the error

main('test.txt') #This works, if the file is in the same folder as the py script

如果与完整目录一起使用(main('C:\Users\文本测试'))代码返回错误AttributeError: 'str' object has no attribute 'exists'。如果我删除带有path.exists()的行,我会得到类似的错误:AttributeError: 'str' object has no attribute 'realpath'。

通过使用文件名main('test.txt'),只要文件与包含函数的python脚本在同一个文件夹中,一切都可以正常工作。在

所以我试着读了docs,它同时表示path.exists()和{}:Changed in version 3.6: Accepts a path-like object.

因为我运行的是3.7.1我向前去检查什么是“类路径对象”:An object representing a file system path. A path-like object is either a str or bytes object representing a path, or an object implementing the os.PathLike protocol. An object that supports the os.PathLike protocol can be converted to a str or bytes file system path by calling the os.fspath() function; os.fsdecode() and os.fsencode() can be used to guarantee a str or bytes result instead, respectively. Introduced by PEP 519.

因此,鉴于我提供了一个字符串,我认为它应该是有效的。我错过了什么?在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值