-1
Import os
source="/storage/emulated/0/converted.py"
destination="/storage/emulated/0/DCIM"
try:
    if os.path.exists(destination):
        print("file already there")
    if os.replace(source,destination):
        print(source+ " was moved")
except FileNotFoundError:
    print(source+ " file was not found")
    

After trying import a file to another I get an error "directory not empty" I am new to coding so I am bit confused,should the destination be empty before importing? and lastly I sometimes get an error saying "not a directory" and I was just wondering if I can only transfer files from directory to directory alone? or can transfer from both(directory and folder)? Thanks in advance for your answer❤️

snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
D-code
  • 3
  • 2
  • If the destination exists, did you want to stop processing after your print()? – JonSG Dec 23 '22 at 16:08
  • [Friendly docs](https://stackoverflow.com/questions/74901615/i-am-trying-to-import-a-file-using-import-os-but-its-keeps-saying-directory-not): ". If dst is a directory, OSError will be raised." Also: "The operation may fail if src and dst are on different filesystems.". You probably want `shutil.move` instead: https://stackoverflow.com/questions/8858008/how-to-move-a-file-in-python#8858026 – Thomas Dec 23 '22 at 16:08
  • Yea both are in the same filesystem but I would try your suggestion also(shutil.move) I appreciate – D-code Dec 23 '22 at 18:01

2 Answers2

2

The os.replace() function will replace the file or directory at the destination path with the file or directory at the source path. If the destination path already exists and is not empty, you will get a "directory not empty" error because the function cannot replace a non-empty directory. So to fix that you can check if not os.listdir(destination) then apply the os.replace(),

Your full code will be something like this-

import os
source = "/storage/emulated/0/converted.py"
destination = "/storage/emulated/0/DCIM"

# Check if the destination path exists
if os.path.exists(destination):
    # If the destination path exists, check if it is empty
    if not os.listdir(destination):
        # If the destination path is empty, call os.replace()
        if os.replace(source, destination):
            print(source + " was moved to " + destination)
    else:
        # If the destination path is not empty
        print("The destination path is not empty")
else:
    # If the destination path does not exist
    print("The destination path does not exist")
A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
0

destination should be the full path of the file i.e.:

destination = "/storage/emulated/0/DCIM/converted.py"

Otherwise you're trying to replace a folder "/storage/emulated/0/DCIM/" with a file "/storage/emulated/0/converted.py"

rnavarro
  • 11
  • 1
  • 4