Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy file to a directory

I want to shutil.copy() function to copy file to another directory. I try to execute the following code:

copy(open("/home/dizpers/pytest/testfile1.txt", "r"), "/home/dizpers/pytest")

But python shell shows me the error message:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/shutil.py", line 116, in copy
    dst = os.path.join(dst, os.path.basename(src))
  File "/usr/lib/python2.7/posixpath.py", line 112, in basename
    i = p.rfind('/') + 1
AttributeError: 'file' object has no attribute 'rfind'

So, I understand why this problem appears. I open the file with open() function. And I think that I also should open a directory like this. How can I do this?

Thanks in Advance!

like image 765
Dmitry Belaventsev Avatar asked Oct 20 '25 16:10

Dmitry Belaventsev


1 Answers

shutil.copy takes in two paths, not a file object and a path, you should just specify the path instead of creating a file object for the first argument

You can use shutil.copyfileobj if you need to use a file object for the first argument, but you'll have to use a file object for the second argument as well.

like image 160
Daniel DiPaolo Avatar answered Oct 22 '25 04:10

Daniel DiPaolo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!