Reputation: 1246
I have a python script that is giving me a hard time on Ubuntu 12.02 with Python 2.7.3.
PS: it runs without problems on Windows.
>>> import os
>>> import shutil
>>> shutil.copy("/mnt/my_network_dive/somewhere/sample.xml", "/mnt/my_network_drive/COMPLETED/")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/shutil.py", line 117, in copy
copyfile(src, dst)
File "/usr/lib/python2.7/shutil.py", line 69, in copyfile
raise Error("`%s` and `%s` are the same file" % (src, dst))
shutil.Error: `/mnt/my_network_dive/somewhere/sample.xml` and `/mnt/my_network_drive/COMPLETED/sample.xml` are the same file
Checking some properties of the files:
>>> os.path.exists("/mnt/my_network_drive/somewhere/sample.xml")
True
>>> os.path.exists("/mnt/my_network_drive/COMPLETED/sample.xml")
True
>>> os.stat("/mnt/my_network_drive/somewhere/sample.xml")
posix.stat_result(st_mode=33272, st_ino=4913809333, st_dev=25L, st_nlink=1, st_uid=1000, st_gid=0, st_size=5447, st_atime=1465311674, st_mtime=1465311674, st_ctime=1465311685)
>>> os.stat("/mnt/my_network_drive/COMPLETED/sample.xml")
posix.stat_result(st_mode=33272, st_ino=4913809333, st_dev=25L, st_nlink=1, st_uid=1000, st_gid=0, st_size=10, st_atime=1465317482, st_mtime=1465317482, st_ctime=1465317483)
>>> os.path.islink("/mnt/my_network_drive/somewhere/sample.xml")
False
>>> os.path.islink("/mnt/my_network_drive/COMPLETED/sample.xml")
False
>>> shutil._samefile("/mnt/my_network_dive/somewhere/sample.xml", "/mnt/my_network_drive/COMPLETED/sample.xml")
False
As you see, calling shutil._samefile
I get False
but shutil.copy
still raise the samefile error
.
Am I forgetting something? Any other way to move or copy files with Python?
Upvotes: 4
Views: 4129
Reputation: 202
In python 3 in shutil.copy there's additional argument follow_symlinks=True Look at this https://docs.python.org/3/library/shutil.html
If follow_symlinks is false, and src is a symbolic link, dst will be created as a symbolic link. If follow_symlinks is true and src is a symbolic link, dst will be a copy of the file src refers to.
Upvotes: 0
Reputation: 37539
It looks like the two files are both hard links to the same file. You can tell because they share the same inode number
st_ino=4913809333
Windows users generally don't create hard links. They are more common in linux environments, which is why you may have not encountered the problem until now.
It is odd that samefile
returns False
. What OS are you using? shutil._samefile
is just a wrapper around os.path.samefile
(on systems where that function exists). What results do you get from os.path.samefile
? On posix systems, it just checks that the device and inode match (which they do in your case) and it should return True
posixpath.py
def samefile(f1, f2):
s1 = os.stat(f1)
s2 = os.stat(f2)
return samestat(s1, s2)
def samestat(s1, s2):
return s1.st_ino == s2.st_ino and s1.st_dev == s2.st_dev
Upvotes: 2