[英]Python create a file in a specific directory
我正在嘗試在特定文件夾中創建文件,但是無論如何,該文件都會在應用程序的路徑中創建。
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()
您在test_folder_path
變量的末尾缺少斜杠,因此創建的文件路徑為cwd\\testfoldertest.txt
而不是cwd\\testfolder\\test.txt
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.