我试图从这个站点复制代码: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,所以我检查了什么是“类似路径的对象”:
表示文件系统路径的对象。类路径对象要么是表示路径的str或字节对象,要么是实现os.PathLike协议的对象。支持os.PathLike协议的对象可以通过调用os.fspath()函数将其转换为str或字节文件系统路径;os.fsdecode()和os.fsencode()可以分别用于保证str或字节结果。由PEP 519介绍。
因此,鉴于我提供了一个字符串,我认为它应该是工作的。那我错过了什么?
发布于 2019-03-08 02:31:43
你的代码:
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的局部变量,如下所示:
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变量名非常常见,很容易发生冲突。
举个很好的例子:
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')发布于 2019-03-08 02:39:18
壳上类型
Type(path)并检查结果和值,可能会将此导入重新定义为变量str。
发布于 2021-10-02 12:49:48
试一试
os.path.exists('C:\\Users\\test.txt')对我来说很有效..。如果对你有用,我就不干了
https://stackoverflow.com/questions/55055792
复制相似问题