python - 如何使用终端运行 py 文件并写入文件
问题描述
我对 python 比较陌生,想测试 python 的基本功能,比如写入和读取文件。使用此代码它完美地工作:
text = "hello there"
file = open("testfile.txt", "w")
file.write(text)
file.close()
接下来我想使用终端运行它。我写了 python3 [fileDir]/testing.py并按下回车键,但不幸的是我无法在 testfile.txt 上得到任何文本。我知道,这可能是一个愚蠢的初学者问题,但请帮助我解决这个问题。
解决方案
假设您的代码在目录中./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
)。
推荐阅读
- java - java.lang.NoClassDefFoundError: OSGI 启动
- r - 如何在 r 中处理 sens.slope 中的 NA?
- multithreading - 飞镖/颤振隔离/未来作为工人
- python - pep8 - 整个项目的统计数据
- prolog - 将一个列表的所有元素复制 N 次到一个新列表 Prolog
- python - 如何在我的 tkinter 文本窗口中打印结果?
- excel - 用户定义的函数在不同的选项卡上返回相同的结果
- java - 从服务传递到组件的角度错误消息
- c++ - R 或 C++ 中的半空间联合和交集
- javascript - Facebook 的 Spark AR Studio 中的垂直平面跟踪