【问题标题】:Save .txt file in local folder by python通过python将.txt文件保存在本地文件夹中
【发布时间】:2021-01-25 02:37:40
【问题描述】:

我想建立一个程序来保存一些文档文件。 我的程序在测试文件夹中运行,我想将文档保存在 test\save 中。 我使用这些方式:

File=open("C:\\test\\save\\hello.txt",'w')
File.write("hello world")
File.close()

现在我将我的程序复制到 E 驱动程序并运行该程序,然后在 C 驱动程序而不是 E 驱动程序中生成 hello.txt。 我应该怎么做才能保存超过我的测试文件夹的每个地方的文档??

【问题讨论】:

  • 你试过open("test\\save\\hello.txt",'w')吗?
  • 确保您的路径正确。无论是驱动器 - C:、E:、D: 等还是您的文件夹。
  • 您的意思是:'File=open("\\test\\save\\hello.txt",'w')'?

标签: python python-3.x


【解决方案1】:

您让程序写入该绝对文件路径。如果您希望它在给定目录中运行,只需将文件名命名为 hello.txt

【讨论】:

    【解决方案2】:

    我猜你想要这样的东西:

    from os.path import dirname, realpath, join
    
    your_current_app_directory = dirname(realpath(__file__))
    your_custom_folder = "test"
    
    with open(join(your_current_app_directory, your_custom_folder, "hello.txt"), "w") as export:
        export.write("hello")
    

    它将是动态的;取决于您的应用目录。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-28
      • 2012-04-04
      • 1970-01-01
      • 2012-04-16
      • 1970-01-01
      相关资源
      最近更新 更多