【问题标题】:Python create a file in a specific directoryPython在特定目录中创建文件
【发布时间】:2019-11-16 20:25:21
【问题描述】:

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

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

【问题讨论】:

    标签: python file directory path


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

      • 谢谢你,我不敢相信我没有看到这个。
      猜你喜欢
      • 2018-07-17
      • 2021-08-31
      • 2013-04-15
      • 1970-01-01
      • 2012-01-13
      • 1970-01-01
      • 2013-01-16
      • 1970-01-01
      • 2019-03-14
      相关资源
      最近更新 更多