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



我正在尝试从此站点重现代码: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

如果与完整目录一起使用(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 我去了foward,检查什么是"路径般的对象":

代表文件系统路径的对象。类似路径的对象是代表路径的str或字节对象,或者是实现OS.Pathike协议的对象。支持OS.Pathike协议的对象可以通过调用OS.FSPATH()函数来转换为str或字节文件系统路径;OS.FSDECODE()和OS.FSENCODE()可以分别用于保证STR或字节结果。由PEP 519。

引入

鉴于我提供了一个字符串,我认为它应该有效。那我缺少什么?

您的代码:

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

它可以正常工作,但是如果您重新定义一个名为"路径"的局部变量,则是这样:

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

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

我建议在import os之后使用os.path,因为路径变量名称非常普遍,因此很容易冲突。

一个很好的例子:

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')

在shell

上键入
Type(path)

并检查结果和价值,也许您将此导入重新定义为变量str。

尝试

os.path.exists('C:\Users\test.txt')

实际上对我有用...如果它适合您

我不这样做

最新更新