Issue
If I have a file.txt And the content looks like this:
BEGAN_SIT
s_alis='HTTP_WSD'
xps_entity='HTTP_S_ER'
xlogin_mod='http'
xdest_addr='sft.ftr.net'
xmax_num='99'
xps_pass='pass'
xparam_nm='htp'
#?SITE END
How i I can loop through it and assign each line for different variable
Solution
some simple string manipulation and splitting will do what you want. I suggest to read up on str.split()
, str.startswith()
, general file handling and list handling
with open("filename") as infile:
for line in infile.read().splitlines():
if line.startswith("s_alis"):
s_alis = line.split("'")[1]
elif line.startswith("xps_entity"):
xps_entity = line.split("'")[1]
#etc
as a function returning a dictionary.
def return_dictionary(filename):
# define empty dict
result = {}
with open(filename) as infile:
for line in infile.read().splitlines():
if line.startswith("s_alis"):
result["s_alis"] = line.split("'")[1]
elif line.startswith("xps_entity"):
result["xps_entity"] = line.split("'")[1]
#etc
return result
list_of_filenames = [
"file1.txt",
"file2.txt"
]
not_sure_what_to_name_this = []
for filename in list_of_filenames:
not_sure_what_to_name_this.append(return_dictionary(filename))
from pprint import pprint
pprint(not_sure_what_to_name_this)
Answered By - Edo Akse Answer Checked By - Mildred Charles (WPSolving Admin)