首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >os.path AttributeError:'str‘对象没有属性“存在”

os.path AttributeError:'str‘对象没有属性“存在”
EN

Stack Overflow用户
提问于 2019-03-08 02:17:40
回答 3查看 33.4K关注 0票数 7

我试图从这个站点复制代码:https://www.guru99.com/python-copy-file.html

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

代码语言:javascript
复制
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,所以我检查了什么是“类似路径的对象”:

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

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2019-03-08 02:31:43

你的代码:

代码语言:javascript
复制
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

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

代码语言:javascript
复制
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

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

我建议在os.path之后使用import os,因为path变量名非常常见,很容易发生冲突。

举个很好的例子:

代码语言:javascript
复制
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')
票数 4
EN

Stack Overflow用户

发布于 2019-03-08 02:39:18

壳上类型

代码语言:javascript
复制
Type(path)

并检查结果和值,可能会将此导入重新定义为变量str。

票数 2
EN

Stack Overflow用户

发布于 2021-10-02 12:49:48

试一试

代码语言:javascript
复制
os.path.exists('C:\\Users\\test.txt')

对我来说很有效..。如果对你有用,我就不干了

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55055792

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档