0

I can write to a file in current directory. I cannot write to a file in a subdirectory. I checked online but the posts and previous questions didn't really help. I have the code below, it should write to File.txt which is inside Subfolder. However, instead of this, I get a new File called "SubFolder\File.txt" in my current directory.

Any help?

PATH = os.getcwd()
PATH+= 'SubFolder\File.txt'
fileInput = open(PATH, "w")
fileOutput = open("SubFolder\File.txt", "w")

I expect a file in a subfolder. I get a file with the desired path as a file name. Can you help? Thanks!

3 Answers 3

2

use double escape for file paths.

fileOutput = open("SubFolder\\File.txt", "w")
Sign up to request clarification or add additional context in comments.

Comments

0

Opening a file for writing doesn't create any intervening subfolders that don't yet exist. You have to create them yourself first, using os.mkdir() (for one level) or os.makedirs() (for multiple levels).

Comments

0

You have to use "os.path.join" as it joins path with '//' or '\' as per required by OS instead of concatenating paths manually. So when file is opened using this PATH then it will go in dir/sub-dir structure instead of creating file named 'sub-dir/filename.exetension' within current directory. I have encountered same issue and this what worked for me.

PATH = os.getcwd()

PATH = os.path.join(PATH,'SubFolder','File.txt')

fileOutput = open(PATH, "w")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.