Skip to main content
 首页 » 编程设计

Python在特定目录中创建文件

2025年05月04日13落叶无声

我正在尝试在特定文件夹中创建一个文件,但无论如何该文件都会在应用程序的路径中创建。

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

请您参考如下方法:

您似乎缺少路径和文件名之间的分隔符。您可以考虑让 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()