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.
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.
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)
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.
import os
my_dir = 'test'
[fun(my_dir) for fun in (os.mkdir, os.chdir)]