简体   繁体   English

如何将 .txt 文件的内容分配给 Python 中的字符串变量?

[英]How can I assign the contents of a .txt file to a string variable in Python?

I couldn't find an answer for this on StackOverflow, so I'm asking this question.我在 StackOverflow 上找不到答案,所以我问这个问题。

I have a text file path stored in a variable called settings_data_path and I want to take whatever is in that text file and put it into a string variable, in this instance, limited_n_ints .我有一个文本文件路径存储在一个名为settings_data_path的变量settings_data_path ,我想将该文本文件中的任何内容放入一个字符串变量中,在本例中为limited_n_ints So I opened the file and put it in a variable using所以我打开文件并将其放入一个变量中

settings_data = open(settings_data_path, "r")
limited_n_ints = (settings_data.read())
print(limited_n_ints)
settings_data.close()

Whenever I opened the data path with w+ and wrote something in the file, everything worked fine.每当我用 w+ 打开数据路径并在文件中写一些东西时,一切正常。 However, when I print limited_n_ints , nothing shows up.但是,当我打印limited_n_ints ,没有任何显示。 Does anyone know how to store this file into a variable?有谁知道如何将此文件存储到变量中?

Try尝试

setting_data = open('inventory.4.txt', 'r')
lines = setting_data.readlines()
limited_n_ints = ''
for i in lines:
  limited_n_ints = limited_n_ints + i
print(limited_n_ints)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何打开文本文件并将其内容分配给 Python function 中的变量? - How can I open a text file and assign it's contents to a variable in a Python function? 无法使用python输入txt文件内容作为查询字符串 - Can't enter txt file contents as query string using python 在Python 3中,如何在单独的.txt文件中搜索字符串? - In Python 3, how can I search for a string in a separate .txt file? 如何使用python访问txt文件中字符串的特定部分? - How can I access specific parts of a string in a txt file with python? 如何使用 python 从 S3 存储桶读取 .txt 文件并查看内容? - How can I read .txt file from S3 bucket using python and view the contents? Python:如何将函数分配给变量? - Python: how can I assign a function to a variable? 如何将 .txt 文件中的特定单词作为字符串变量导入 Python? - How do I import a specific word from a .txt file into Python as a string variable? 如何将字符串转换为对变量的调用并检索变量内容? - How can I turn a string into a call to a variable and retrieve the variable contents? 如何在 .txt 文件中搜索字符串并打印字符串所在的行? (Python) - How can I search for a string inside a .txt file and print the line where the string is in? (Python) 如何将python 3.6中的变量更新为.txt文件中的文本字符串 - How to update a variable in python 3.6 to that of a string of text in a .txt file
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM