os.path AttributeError: 'str' 对象没有属性 'exists'

ZeC*_*oca 6 python

我正在尝试从此站点重现代码:https : //www.guru99.com/python-copy-file.html

一般的想法是使用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
Run Code Online (Sandbox Code Playgroud)

如果与完整目录一起使用 (main('C:\Users\test.txt')) 代码返回错误AttributeError: 'str' object has no attribute 'exists'。如果我删除该行,path.exists()我会收到类似的错误:AttributeError: 'str' object has no attribute 'realpath'. 通过使用文件名,main('test.txt')一切正常,只要文件与包含该函数的 python 脚本位于同一文件夹中。

所以我尝试阅读文档,其中说明了path.exists()path.realpath()

在 3.6 版更改: 接受一个类似路径的对象。

由于我正在运行 3.7.1,我继续检查什么是“类似路径的对象”:

表示文件系统路径的对象。类路径对象要么是表示路径的 str 或 bytes 对象,要么是实现 os.PathLike 协议的对象。支持 os.PathLike 协议的对象可以通过调用 os.fspath() 函数转换为 str 或 bytes 文件系统路径;os.fsdecode() 和 os.fsencode() 可分别用于保证 str 或 bytes 结果。由 PEP 519 引入。

从那以后,鉴于我提供了一个字符串,我认为它应该可以工作。那么我缺少什么?

DDG*_*DGG 7

你的代码:

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
Run Code Online (Sandbox Code Playgroud)

它工作正常,但如果您重新定义一个名为 path 的局部变量,如下所示:

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)

# The path variable here overrides the path in the main function.
path = 'abc'  

main('C:\\Users\\test.txt')  # This raises the error
Run Code Online (Sandbox Code Playgroud)

我猜这只是你的代码,显然这是一个错误的例子。

我建议使用os.pathafter import os,因为路径变量名很常见,很容易发生冲突。

举一个很好的例子:

import shutil
import os


def main(filename):
    if os.path.exists(filename):
        src = os.path.realpath(filename)
        head, tail = os.path.split(src)
        dst = src + ".bak"
        shutil.copy(src, dst)

main('C:\\Users\\test.txt')
main('test.txt')
Run Code Online (Sandbox Code Playgroud)