How can I assign the contents of a .txt file to a string variable in Python?
Question:
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
. 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 open the data path with w+ and write something in the file, everything worked fine. However, when I print limited_n_ints
, nothing shows up. Does anyone know how to store this file in a variable?
Answers:
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)
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
. 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 open the data path with w+ and write something in the file, everything worked fine. However, when I print limited_n_ints
, nothing shows up. Does anyone know how to store this file in 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)