You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyCharm中如何放置资源文件以实现src与test共同访问

解决方案

无需移动文件位置,修改board.py的路径写法即可

保持words.txt在src/scrabble目录下(和board.py同目录),修改board.py中读取文件的代码,基于脚本自身位置生成绝对路径,而非依赖当前工作目录的相对路径。

方法1:使用os模块(兼容所有Python版本)

import os

# 获取board.py所在的绝对目录
script_dir = os.path.dirname(os.path.abspath(__file__))
# 拼接words.txt的完整路径
words_path = os.path.join(script_dir, 'words.txt')

with open(words_path) as file:
    # 你的文件读取逻辑
    content = file.read()

方法2:使用pathlib(Python 3.4+推荐,语法更简洁)

from pathlib import Path

# 获取board.py所在目录,拼接words.txt路径
words_path = Path(__file__).parent / 'words.txt'

with open(words_path) as file:
    # 你的文件读取逻辑
    content = file.read()

原理说明

  • __file__是Python内置变量,会返回当前脚本(此处为board.py)的绝对路径,不受运行入口影响——不管是直接运行board.py,还是通过test_board.py调用board.py,这个路径始终准确。
  • 通过os.path.dirname()或Path(__file__).parent拿到脚本所在目录,再拼接words.txt,就能得到永远正确的文件路径,无需修改PyCharm配置,其他用户克隆项目后直接运行代码即可正常访问文件。

内容的提问来源于stack exchange,提问作者Peter Drake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 00:59:57