1

I'm trying to create a file in a specific folder, but the file will create in the app's path no matter what.

path = os.getcwd()
while not os.path.exists(path + "\\testfolder"):
    os.mkdir(path + "\\testfolder")

test_folder_path = path + "\\testfolder"
test_file = open(test_folder_path + "test.txt", "w")
test_file.write("test")
test_file.close()

2 Answers 2

3

It seems you're missing a separator between the path and the file name. You could consider letting os.path.join do the heavy lifting for you:

cwd = os.getcwd()
targetPath = os.path.join(cwd, testfolder);
while not os.path.exists(targetPath):
    os.mkdir(targetPath)

targetFile = os.path.join(targetPath, 'test.txt')
testFile = open(targetFile "w")
testFile.write("test")
testFile.close()
Sign up to request clarification or add additional context in comments.

Comments

1

You are missing a slash at the end of the test_folder_path variable, so the created file path is cwd\testfoldertest.txt instead of cwd\testfolder\test.txt

1 Comment

Thank you , i can't belive i didn't see this.

Your Answer

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