-1

Is there a more concise way to create a new directory and change to that directory than:

import os

os.mkdir(my_dir)
os.chdir(my_dir)

I know it's just one extra line of code, but I'd like to tighten up if I can.

JayCo741
  • 583
  • 2
  • 6
  • 20
  • 4
    Just curious: Why? What's wrong with two lines? If you're using it so much that it bothers you, you can just write a function that calls these two. – Pranav Hosangadi Jul 13 '21 at 19:58
  • 3
    Python is not the first language that comes to mind when you want to save on lines. – bereal Jul 13 '21 at 20:02
  • 1
    I’m voting to close this question because Stack Overflow's scope is limited to _practical_, answerable questions. Saving lines at the expense of readability is contrary to the zen of python and understood best practice -- it's inherently impractical. – Charles Duffy Jul 13 '21 at 20:11

3 Answers3

3

You can define your own wrapper around the two functions:

import os

def a(b):
    os.mkdir(b)
    os.chdir(b)

Now, whenever you want to create a new directory and change to that directory, use

a(directory)

Also, if you'd really like to achieve that in one line, use

os.mkdir(you_are_welcome); os.chdir(you_are_welcome)
Captain Trojan
  • 2,800
  • 1
  • 11
  • 28
0

os methods related to file and directory manipulation do not return any object, thus they don't allow for chaining.

Your best option for this specific case is to embed your methods in a function, as others already said (well your best option is to do nothing imho).

But if you'd like to take this a step further and you're willing to adapt os functionalities to method chaining, you could define a sort of decorator that returns the os module at the end of the given function:

def return_path(func):
    def wrapper(*args, **kwargs):
        func(*args, **kwargs)
        return os
    return wrapper

os.mkdir = return_path(os.mkdir)

This way os.mkdir() supports method chaining:

os.mkdir(my_dir).chdir(my_dir)

This is just a possible way to customize a built-in behaviour through overriding; it is definitely an overwork for such a problem.

I suggest you keep your program as a clear and well structured set of instructions. As a general coding practice, do not sacrifice clarity for the sake of conciseness, e.g. multiple statements on the same line are bad for PEP8, and for a good reason.

Max Shouman
  • 1,333
  • 1
  • 4
  • 11
-1
import os

my_dir = 'test'
[fun(my_dir) for fun in (os.mkdir, os.chdir)]
wagnifico
  • 632
  • 3
  • 13