【问题标题】:Creating a python file in a local directory在本地目录中创建 python 文件
【发布时间】:2013-05-07 23:29:33
【问题描述】:

好的,所以我基本上是在编写一个创建文本文件的程序,但我希望将它们创建在与 .py 文件位于同一文件夹中的文件夹中,这可能吗?我该怎么做? 使用 python 3.3

【问题讨论】:

标签: python file


【解决方案1】:

要查找脚本所在的目录:

import os

path_to_script = os.path.dirname(os.path.abspath(__file__))

然后你可以用它作为你的文件名:

my_filename = os.path.join(path_to_script, "my_file.txt")

with open(my_filename, "w") as handle:
    print("Hello world!", file=handle)

【讨论】:

  • +1。但值得指出的是,在您完成任何可能更改工作目录的操作后,您不能信任 __file__。如果您不确定这意味着什么,请完全按照此示例执行操作,调用 abspath 并在开始时将其保存在变量中,然后稍后再使用该变量。
  • 另外,print >> handle, "Hello world!"SyntaxError。 OP 使用的是 Python 3.3。请改用print("Hello world!", file=handle)
【解决方案2】:

使用open:

open("folder_name/myfile.txt","w").close()  #if just want to create an empty file

如果你想创建一个文件,然后用它做一些事情,那么最好使用with 语句:

with open("folder_name/myfile.txt","w") as f:
    #do something with f

【讨论】:

  • 如果文件已经存在并且有任何内容,执行open(filename, 'w').close() 将截断文件。使用open(filename, 'a').close() 更安全。
猜你喜欢
  • 2019-11-16
  • 2013-10-11
  • 1970-01-01
  • 2017-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-06
  • 2021-09-29
相关资源
最近更新 更多