gpt4 book ai didi

python - 我将如何在 python 的模块中加载文本文件?

转载 作者:太空宇宙 更新时间:2023-11-04 09:38:10 25 4
gpt4 key购买 nike

我有一个包含多个模块的 python 项目,一个模块包含一个包含一长串关键字的 .txt 文件。

我如何访问 .txt 文件并将其内容(字符串列表)加载到另一个位置(不同目录)的 .py 脚本中的变量中?

--- Library
- Module_Alice
- etc..
- Module_Bob
- assets
- audio
- video
- texts
- all_keywords.txt
- unittests
- func
- test_text_process.py

我需要将 all_keywords.txt 中的所有关键字加载到 test_text_process.py 中的变量中

最佳答案

使用打开

可以使用绝对路径:

with open("/root/path/to/your/file.txt",'r') as fin:
# Your reading logic

或者你可以使用相对路径:

with open("../../your/file.txt",'r') as fin:
# read it.

如果您要移动文件夹并在其他地方运行它,但不是在 python 文件级别,您可能希望以这种方式进行相对导入:

import os.path as path
text_file_path = path.dirname(path.abspath(__file__)) + '/assets/texts/all_keywords.txt'

这样你就可以在任何地方运行你的 python 文件并且仍然能够使用文本文件。如果你只是做一个亲戚,你不能从它的目录之外运行你的 python,比如 python path/to/script.py

关于python - 我将如何在 python 的模块中加载文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52877913/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com