Reputation: 855
I want to write a program that goes to the Desktop folder, and do commands like make a folder. I have this:
import os
def run_command(command):
os.system(f'cmd /c "{command}"')
"""
This command is running in the folder of this Python file, thus I can only access folders from this directory.
But I want it to go to the Desktop folder and make a new directory there.
"""
run_command("cd Desktop") # It makes an error "The system cannot find the path specified."
run_command("md Folder")
r"""I want the directory to be C:\Users\<username>"""
As you can see in the comments, it does everything in the directory you ran this Python file. But I want the directory to be "C:\Users<username>". This is what you get if your open cmd prompt manually. How do I make its directory be "C:\Users<username>"? Or if there is a better way, how do I do it?
Thank you for helping.
Upvotes: 2
Views: 3302
Reputation: 502
Like James said, os.chdir
should work. But you should keep in mind that the character \
is an escape character, and in order to use it, the string must be prefixed with a r: r"C:\Users\user"
or it must be escaped: "C:\\Users\\user"
.
Also a easy way to get the current user is by using the built-in getpass
module.
import getpass
print(getpass.getuser())
Upvotes: 2
Reputation: 16236
This code makes use of environment variables to get the correct Desktop directory and to invoke the correct command processor.
It also uses os.path.join
to create the directory path. Since Desktop
is hardcoded, a REVERSE SOLIDUS (backslash) could probably also be hardcoded. But, making a practice of using os.path.join
will make code portable to all systems on which Python runs.
import os
def run_command(command):
os.chdir(os.path.join(os.environ['USERPROFILE'], 'Desktop'))
os.system(os.environ['ComSpec'] + ' /c "cd"')
Upvotes: 1
Reputation: 36608
Use os.chdir
to change the directory that Python is "running in".
os.chdir('C:\Users\someuser')
Upvotes: 1