首页 > 解决方案 > 如何使用 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()

标签: pythonpython-3.xfilepython-os

解决方案


可以使用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函数说,“与脚本相同的目录,但使用此名称”


推荐阅读