首页 > 解决方案 > 如何使用终端运行 py 文件并写入文件

问题描述

我对 python 比较陌生,想测试 python 的基本功能,比如写入和读取文件。使用此代码它完美地工作:

text = "hello there"
file = open("testfile.txt", "w")
file.write(text)
file.close()

接下来我想使用终端运行它。我写了 python3 [fileDir]/testing.py并按下回车键,但不幸的是我无法在 testfile.txt 上得到任何文本。我知道,这可能是一个愚蠢的初学者问题,但请帮助我解决这个问题。

标签: pythonfileterminalraspberry-pi

解决方案


假设您的代码在目录中./test-dir。因此,相对于当前目录的文件树是:

.
└── test-dir
    └── testing.py

1 directory, 1 file

如果你运行python test-dir/testing.py,你当前的工作目录.(这里,.表示你当前所在的目录,它的父目录test-dir)。因此,路径somefile.txt将在 中.,而不是在 中./test-dir

跑步:

python test-dir/testing.py

将您的目录结构更改为:

.
├── test-dir
│   └── testing.py
└── testfile.txt

1 directory, 2 files

通常,代码中的所有路径都将被解释为相对于您运行 Python 命令的目录(ie .),而不是 Python 源文件所在的目录 (ie ./test-dir)。


推荐阅读