-2

I'm trying to change directory when calling a python file in cmd but it's not working ! I tried all types of slashes & back slashes & escaping, sometimes when the code runs, the directory isn't changing and stays the same where i start the py file and sometimes the code isn't running and i have this error Error

import os
#import sys

os.chdir('%SystemRoot%/Users/%username%/AppData/Local/Google/Chrome/User Data')
os.system('cd \"%SystemRoot%\\Users\\%username%\\AppData\\Local\\Google\\Chrome\\User Data\"')

I tried to change the system variables %SystemRoot% and %username% to words like C:/ and user2 (my system root and user name ) but still not working ! Can anyone try it in his computer and tell me what to change pls ? Thanks !

  • So, you start a shell (Windows cmd prompt), run the Python program and then want to have the current working directory in the shell changed? Impossible. Maybe what you want to achieve with this is possible, but discussing that would require you to describe that (keyword "XY problem"). – Ulrich Eckhardt Jun 23 '22 at 18:13
  • @UlrichEckhardt It's an aumatisation project, we have clients and i have to access the names of all (specially the last) google chrome profiles created, i created a cmd script that goes to a specified path and list all the directories (but i get all of this in cmd output and i don't know how to access the last element name with cmd output and use it in a python code) cd "C:\Users\%username%\AppData\Local\Google\Chrome\User Data" dir seedsProfiles /AD /b I'm having the chrome profiles list as cmd output but i dont' know how to access the name of the last item in cmd ! or send to python code – Soufiane El Himani Jun 24 '22 at 08:39
  • Please [edit] your question to clarify that. Write separate paragraphs explaining your environment, your task, what you attempted and how it fails. Use small and simple sentences. Do not use strings of multiple statements without a period (".") in between. – Ulrich Eckhardt Jun 24 '22 at 14:21

1 Answers1

1

Python does not automatically expand shell variables like %SystemRoot% and %username% to their actual values, this is what caused the error you were getting. Try os.chdir(os.path.expandvars(os.path.expanduser('%SystemRoot%/Users/%username%/AppData/Local/Google/Chrome/User Data'))) for the first line as this should expand the %username% and %SystemRoot% variables to a valid path.
EDIT: Sorry, I misunderstood your question. While this will take care of the error you were getting, you cannot change the shell's working directory from your script; see comment under your question by Ulrich Eckhardt

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 24 '22 at 10:45