简体   繁体   English

Python在特定目录中创建文件

[英]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: 您可以考虑让os.path.join为您完成繁重的工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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