0

I want to change my current working directory during the execution of the the script to my Desktop.

I used:

import os

os.chdir("C:\Documents and Settings\%username%\Desktop")

but its showing ERROR 3

WindowsError: [Error 3] The system cannot find the path specified: 'C:\\Documents and Settings\\%username%\\Desktop'
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
adnaan.zohran
  • 809
  • 9
  • 21
  • 2
    Because there isn't a user named %username% – Zimm3r Oct 12 '13 at 07:41
  • i want this code to work on multiple machines. I can't hard code my username in the script.. Is there any way to generalise this. above works in cmd so I thought it might work in python too. – adnaan.zohran Oct 12 '13 at 07:43
  • `%username%` is an environment variable. You will have to expand it within the pathname. – AdrianHHH Oct 12 '13 at 08:14

2 Answers2

1

From this post, it looks like you need this (I'm on a mac, so I can't test this myself):

import getpass
import os

os.chdir("C:\Documents and Settings\%s\Desktop" %getpass.getuser())
Community
  • 1
  • 1
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
0

I recommend doing this way:

import os

os.chdir(os.path.expandvars("C:\Documents and Settings\${username}\Desktop"))

This solution is more generic because it would work for any environment variable.

Chris Wolf
  • 1,539
  • 2
  • 10
  • 9