如何循环和索引Python中的文件内容,并为不同的变量分配每行

omjgkv6w  于 2022-09-21  发布在  Python
关注(0)|答案(1)|浏览(169)

如果我有一个file.txt,内容如下:

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

如何遍历它并将每一行赋给不同的变量

byqmnocz

byqmnocz1#

一些简单的字符串操作和拆分将完成您想要的操作。我建议阅读str.split()str.startswith()、通用文件处理和列表处理

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

作为返回词典的函数。

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)

相关问题