I'm trying to reproduce the code from this site: https://www.guru99.com/python-copy-file.html
The general idea is to copy a file using python. Although I can work my way around the errors, I also want to understand what I'm doing wrong in this case.
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
If used with the full directory (main('C:\Users\test.txt')) The code returns the error AttributeError: 'str' object has no attribute 'exists'
. If I remove the line with path.exists()
I get a similar error: AttributeError: 'str' object has no attribute 'realpath'
.
By using the filename main('test.txt')
everything works, as long as the file is in the same folder as the python script that contains the function.
So I tried reading the docs, which states for both path.exists()
and path.realpath()
:
Changed in version 3.6: Accepts a path-like object.
Since I'm running 3.7.1 I went foward to check what is a "path-like object":
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.
From that, given that I provided a string, I take it should be working. So what I'm missing?
path
in one version of your code and completely forgot about it.print(type(path))
just ahead of the first use. I expect that will producestr
rather than apath
object. If so, you need to trace the definition ofpath
back to its source. Your posted code does not show this problem.