【问题标题】:Opening a file in a folder in Python?在 Python 中打开文件夹中的文件?
【发布时间】:2015-03-13 11:36:42
【问题描述】:

我想打开一个要写入的文件。

with open(oname.text , 'w') as f:

现在我想将文件写入文件夹"Playlist"

我知道我必须使用os.path但我不知道如何使用它

全部

【问题讨论】:

  • os.chdir('Playlist')

标签: python text copy directory


【解决方案1】:
path = os.path.join('Playlist', oname.text)
with open(path, 'w') as f:
    ...

如果您不确定当前目录的'Playlist' 子目录是否已经存在,请在其前面加上:

if not os.path.isdir('Playlist'):
    if os.path.exists('Playlist'):
        raise RuntimeError('Playlist exists and is a file, now what?!')
    os.mkdir('Playlist')

如果'Playlist' 确实存在但作为文件而不是目录存在,则会引发异常——按您的意愿处理这种异常情况,但除非您删除或重命名文件,否则您将无法拥有它也是一个目录!

如果您想要的路径有多个级别的目录,请使用 os.makedirs 而不是 os.mkdir,例如 Play/List/Whatever(您可以使用它以防万一)。

【讨论】:

    【解决方案2】:

    您可以使用os.chdir 函数更改当前工作目录。

    os.chdir('Playlist')
    with open(oname.text , 'w') as f:
        ...
    

    【讨论】:

      【解决方案3】:

      使用with 语句和os.path.join 方法

      dir_path =  "/home/Playlist"
      file_path = os.path.join('dir_path, "oname.txt")
      content = """ Some content..."""
      with open(file_path, 'wb') as fp:
          fp.write(content)
      

      fp = open(file_path, "wb"):
      fp.write(content)
      fp.close()
      

      【讨论】:

        猜你喜欢
        • 2014-11-07
        • 2018-01-27
        • 1970-01-01
        • 2011-10-10
        • 2011-10-01
        • 1970-01-01
        • 2013-05-06
        • 1970-01-01
        相关资源
        最近更新 更多