OSError: Directory not empty promoted, how to fix?

I'm just trying to write a small application that takes a value from a file called "DATA.DAT" and renames the folder containing this file with that value.

The .py script runs in a different folder and allows the user to specify the path. To give you a better idea, the user path should look like (on Mac) '/ Users / User / Desktop / FOLDER' and 'FOLDER' should contain 'DATA.DAT'.

Here's what a small portion of the source code looks like:

try: data = open('DATA.DAT').read() data_data = data[12:17] path_paths = path.rsplit('/') basepath = '/'.join(path_paths[:-1]) chdir(basepath) if path_paths[-1] <> data_data: rename(path_paths[-1], data_data) raw_input('Folder name has been corrected! Thank you.') quit() else: print('Folder name was already correct! Thank you.') quit() except IndexError: raw_input('ERROR!') quit() 

Well, it works; but this is a raise and exception when "FOLDER" contains more than one file (in fact, "FOLDER" should contain only "DATA.DAT" and other folders. This does not give problems.) ...

 Traceback (most recent call last): File "/Users/User/Desktop/example.py", line 72, in <module> rename(path_paths[-1], data_data) OSError: [Errno 66] Directory not empty 

Just to prevent this from happening, is there a way to fix this? Thanks.

+4
source share
2 answers

Edit: The correct shutil.move tool:

 shutil.move(path_paths[-1], data_data) 

Assuming path_paths[-1] is the absolute directory you want to rename, and data_data is the absolute name of the directory you want to rename to.

The target directory should not exist for this. These two locations do not have to be on the same file system.


Old answer: use os.renames instead of os.rename .

It will recursively create any necessary directories.

+13
source

It is much easier to use shutil .

+2
source

All Articles