【问题标题】:How to Open/Read/Write Files in a Folder in Parent Directory in Python?如何在 Python 中打开/读取/写入父目录中的文件夹中的文件?
【发布时间】:2020-07-16 17:18:02
【问题描述】:

我想打开/读取/写入位于父目录文件夹中的文件:

这是我的文件树:

HiLo v2.00/
┣ Data/
┣ Files/
┃ ┣ __pycache__/
┃ ┃ ┣ __init__.cpython-38.pyc
┃ ┃ ┣ config.cpython-38.pyc
┃ ┃ ┣ menu.cpython-38.pyc
┃ ┃ ┗ score.cpython-38.pyc
┃ ┣ __init__.py
┃ ┣ config.py
┃ ┣ game.py
┃ ┣ menu.py
┃ ┗ score.py
┣ __pycache__/
┃ ┣ config.cpython-38.pyc
┃ ┣ game.cpython-38.pyc
┃ ┗ score.cpython-38.pyc
┗ setup.py

我想打开/读取/写入Data/ 文件夹中的文件。我如何从Files/menu.py打开它?

【问题讨论】:

    标签: python-3.x io


    【解决方案1】:

    这听起来像你要找的东西Get parent of current directory from Python script

    连同https://stackabuse.com/introduction-to-the-python-pathlib-module/

    from pathlib import Path
    d = Path(__file__).resolve().parents[1]
    print(d)
    d = d / 'Data' / 'yourfile.txt'
    print(d)
    with d.open() as file:
        print(file.read())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-03-29
      • 1970-01-01
      • 1970-01-01
      • 2014-09-18
      • 2014-04-16
      • 2019-12-20
      • 1970-01-01
      相关资源
      最近更新 更多