python - 如何使用 os 库获取当前工作目录并在其上写入 .txt 文件?
问题描述
我想找到带有 os 库的当前工作目录(cwd)并在其上写入 .txt 文件。
像这样的东西:
import os
data=["somedatahere"]
#get_the_current_directory
#if this_is_the_current_directory:
new_file=open("a_data.txt", "a")
new_file.write(data)
new_file.close()
解决方案
可以使用os
库来完成,但pathlib
如果您使用的是 Python 3.4 或更高版本,则新的更方便:
import pathlib
data_filename = pathlib.Path(__file__).with_name('a_data.txt')
with open(data_filename, 'a') as file_handle:
file_handle.write('Hello, world\n')
基本上,该with_name
函数说,“与脚本相同的目录,但使用此名称”。
推荐阅读
- python-3.x - 这个函数的时间复杂度是多少,它生成一个数字的所有唯一因子组合?
- gitlab - 访问模板中设置的环境变量
- r - 在闪亮的仪表板标题部分中添加闪亮的小部件
- laravel - 服务器中laravel项目中的子目录
- reactjs - Opentok React:如何调用OTPublisher的Publisher对象的getStats方法?
- postgresql - Laravel 模型使用 ltrees 的 postgresql `subpath` 函数获取子路径
- javascript - 使用来自对象的行创建表
- javascript - ios上的jQuery滚动问题
- simulink - dsPIC 挂起带有 simulink 代码生成器的扩展卡尔曼滤波器
- database - TYPO3 Extbase 查询总是超级慢