一般的想法是使用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.
因此,鉴于我提供了一个字符串,我认为它应该是有效的。我错过了什么?在