2

I am using the os.replace function to rename a folder. The folder will remain in the same parent directory.

parent_dir = '/Users/my_Username/Desktop/'
old_name = 'foo'
new_name = 'bar'
os.replace(parent_dir + old_name, parent_dir + new_name)

This code works, but feels a little redundant, especially when using long variable names and when calling this function multiple times.

According to the docs,

This function can support specifying src_dir_fd and/or dst_dir_fd to supply paths relative to directory descriptors.

However, I cannot figure out how to pass in the relative path of both folders. I thought it would be something like this:

os.rename(old_name, new_name, src_dir_fd=parent_dir)

But that doesn't work.

How do I pass in a relative path?

Peter Schorn
  • 916
  • 3
  • 10
  • 20

1 Answers1

1

You could write something like this:

import os

parent_dir = '/Users/my_Username/Desktop/'
old_name = 'foo.txt'
new_name = 'bar.txt'

with os.open(parent_dir, os.O_RDONLY) as fd:
    os.replace(old_name, new_name, src_dir_fd=fd)

Option src_dir_fd accepts a file descriptor (fd), intead of actual path. There is good description in the documentation.

funnydman
  • 9,083
  • 4
  • 40
  • 55
  • 1
    Thanks for the response! I did read the documentation you linked in your answer, but it's still not entirely clear to me what a file descriptor is. How to I transform a file path into a file descriptor and what does one look like? – Peter Schorn Jan 26 '20 at 08:14
  • @PeterSchorn check out this question: https://stackoverflow.com/questions/5256599/what-are-file-descriptors-explained-in-simple-terms – funnydman Jan 26 '20 at 08:16