user11629539
user11629539

Reputation:

Python create a file in a specific directory

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()

Upvotes: 1

Views: 5718

Answers (2)

Mureinik
Mureinik

Reputation: 311123

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()

Upvotes: 3

DeepSpace
DeepSpace

Reputation: 81594

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

Upvotes: 1

Related Questions