Ask your own question, for FREE!
Computer Science 7 Online
OpenStudy (dmw_ocw):

With this code the file is created in the current directory where idle was started: program firstFile.py, shown below: outFile = file('sample.txt', 'w') outFile.write('My first output file!') outFile.close() I could add a path like /home/user/sample.txt and the file would be created there. How would I used a variable for the file path instead?

OpenStudy (espex):

Use a string variable and request the path from the user.

OpenStudy (dmw_ocw):

Is there a way I can hardcode the path, so say I prompt the user for a filename can I enter a path and add the filename variable they gave at the end?

OpenStudy (espex):

Certainly, if you know the path will always be "C:\Python\<something>" then you can set a variable, root, equal to the root path (root = "C:\Python\") and then prompt the user for a sub-directory. Take the user input and concatenate it to a new string, path = root + input, but be sure to have something to handle the event the directory doesn't exist.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!