簡體   English   中英

Python在特定目錄中創建文件

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM