简体   繁体   中英

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

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

您在test_folder_path变量的末尾缺少斜杠,因此创建的文件路径为cwd\\testfoldertest.txt而不是cwd\\testfolder\\test.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM