test_qweqwe
test_qweqwe

Reputation: 47

How to troubleshoot "NotADirectoryError: [Errno 20] Not a directory:"?

I don't understand why I'm receiving this an error.

Error:

File "/home/user/my_script.py", line 37, in my_script
    os.replace(temp_file.name, file_name)
NotADirectoryError: [Errno 20] Not a directory: '/home/user/folder/tmpep07qkgk' -> '/home/user/folder/'

My code:

file_name = config['filename']
file_format = config['format']

if file_format == 'yml':
    with tempfile.NamedTemporaryFile(mode='w', dir=os.path.dirname(file_name), delete=False) as temp_file:
        yaml.safe_dump(convert_to_dict(data), temp_file)
    os.replace(temp_file.name, file_name) # LINE 37
    logger.info('Saved to file: {}'.format(file_name))

Upvotes: 2

Views: 54178

Answers (1)

abdusco
abdusco

Reputation: 11091

Make sure file_name is a file path. Both parameters of os.rename have to be either a file path or a directory path. Or you'll get an error.

Here's a working example

import tempfile
import os

t = tempfile.NamedTemporaryFile('a')

dest_dir = os.path.expanduser('~')
dest_path = os.path.join(dest_dir, 'saved.yml')

print(t.name)
print(dest_path)

os.replace(t.name, dest_path)

print(os.path.isfile(dest_path))

output:

C:\Users\x\AppData\Local\Temp\tmpwcs1m87w
C:\Users\x\saved.yml
True

Upvotes: 2

Related Questions