-2

I want to copy a file from a folder, one directory above the python script being interpreted, to a folder in the same directory the python script lives.

This is the folder structure.

-----/A
---------copyme.txt
-----/test
----------myCode.py
---------/B

I want to copy file copyme.txt, from folder A, to folder B, under the test folder.

This is the code i tried:

import os
import shutil

shutil.copyfile('../A/copyme.txt', '/B')

However, i received this error:

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    shutil.copyfile('../A/copyme.txt', 'B')
  File "/home/user1/anaconda3/lib/python3.8/shutil.py", line 261, in copyfile
    with open(src, 'rb') as fsrc, open(dst, 'wb') as fdst:
IsADirectoryError: [Errno 21] Is a directory: 'B'
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
user1584421
  • 3,499
  • 11
  • 46
  • 86
  • 1
    yes, you copy a file to a directory, try a file to another file – Petronella Apr 06 '21 at 15:05
  • Check this shutil.copyfile('../A/copyme.txt', '../B') – Saurav Rai Apr 06 '21 at 15:11
  • 1
    Check the [documentation](https://docs.python.org/3/library/shutil.html#shutil.copyfile) : it states *dst must be the complete target file name; look at copy() for a copy that accepts a target directory path. If src and dst specify the same file, SameFileError is raised.* So if you want to copy with the same name just use `shutil.copy()` instead of `shutil.copyfile()` – Luis Blanche Apr 06 '21 at 15:15
  • @SauravRai I tried your approach, but it just copies the file to the parent folder of folder `A` and renames the filename as `B`. – user1584421 Apr 06 '21 at 15:29
  • @LuisBlanche I truied your code and i get `PermissionError: [Errno 13] Permission denied: '/B'` – user1584421 Apr 06 '21 at 15:30
  • Well this is another problem then, this means your user does not have rights over that folder. If you are on a unix system you can fix that using `chmod` or `chown` commands if you have sudo rights. – Luis Blanche Apr 06 '21 at 16:44

1 Answers1

1

Get the current dir path and add the src path and dest path to it.

Ex:

import os
import shutil

BASE_PATH = os.path.dirname(os.path.realpath(__file__))

shutil.copyfile(os.path.join(BASE_PATH, "..", "A", "copyme.txt"),
                os.path.join(BASE_PATH, "B", "copyme.txt"))
Rakesh
  • 81,458
  • 17
  • 76
  • 113