[英]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.