英文:
How to store .txt data permanently within python code?
问题
我正在编写一个用Python编写的脚本,它会读取一个大的.txt文件,并将文件中的信息编译成一个列表。这个文件需要在每次运行脚本时都被读取,但不会发生改变。是否有一种方法可以将这个文件合并到我的代码中,以便其他人在他们的计算机上运行脚本时,只需要执行文件,而不需要同时拥有可执行文件和.txt文件?
我想避免手动将这个.txt文件输入到一个列表声明中,因为这将非常耗时。
英文:
I am writing a script in python that reads a large .txt file and compiles the information in the file into a list. This file needs to be read any time the script is ran, and never changes. Is there some way for me to incorporate this file into my code, such that if other people run the script on their computers, they only need to have the executable, and not both the executable and the .txt file?
I would like to avoid manually entering this .txt file into a list declaration, as this would be very time consuming.
答案1
得分: 1
你可以将文件保存在项目目录中,以便从代码中访问。在这种情况下,文件将与您的代码一起保留。
目录可能如下所示:
- 项目
- 文档
- file.txt
- main.py
然后在您的代码中可以这样做:
with open(docs/file.txt, 'r') as f:
# 对文件进行操作
请注意,如果您选择这种方式,您的代码将依赖于您的目录结构。
或者,您可以简单地创建一个多行字符串,将其粘贴到Python文件中作为变量并访问它。
类似这样:
my_file_string = '''一些很长的字符串'''
# 对字符串进行操作
我还想指出,严格来说,这两种方法都不是“最佳”解决方案,但如果您需要快速操作或者在一个小型项目上工作,这是一个处理问题的好方法。鉴于您提出问题的方式,这应该能解决您的问题。祝你好运!
英文:
You can save the file within your project directory to be accessible from the code. In this case, the file simply would stay with your code.
The directory could look like:
-project
- docs
- file.txt
- main.py
Within your code then you can do:
with open(docs/file.txt, 'r') as f:
# do something with the file
Be aware that if you choose this your code is then dependent on your directory structure.
Alternatively, you can simply create a multiline string and paste it into a python file as a var and access it.
Something like:
my_file_string = '''some long string'''
# do something with the string
I would also like to note that neither of these is the "best" solution strictly speaking, but it's a good way to handle things if you are working fast or on a small project. Given the way you phrased your question, this should solve your issue. Good luck!
答案2
得分: 1
我希望避免手动输入这个 .txt 文件到一个列表声明中,因为这将非常耗时。
使用 pprint
打印出你的结果列表一次。你可以配置 pprint
来包装列表或保持它紧凑。输出将看起来像一个列表,你可以复制到你的脚本中并赋值给一个变量,你永远不需要再次处理它或包含额外的文件。
https://onlinegdb.com/CRtyashM4
英文:
>I would like to avoid manually entering this .txt file into a list declaration, as this would be very time consuming.
use pprint
to print out your resulting list one time. you can configure pprint
to wrap the list OR keep it compact. the output will look like a list that you can copy into your script and assign to a variable you never have to process again or include an extra file.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论