Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python,对文件进行排序_Python - Fatal编程技术网

Python,对文件进行排序

Python,对文件进行排序,python,Python,我想制作一个函数,对文件中的数据进行排序,并将其放入字典中。我已作出以下声明: def fileread(filename, filetype, readlist): returnslist = {} with open(filename + "." + filetype, "r") as f: for line in f: for entry in readlist: if(line[:(entry.len() + 2)] == entry):

我想制作一个函数,对文件中的数据进行排序,并将其放入字典中。我已作出以下声明:

def fileread(filename, filetype, readlist):
returnslist = {}
with open(filename + "." + filetype, "r") as f:
    for line in f:
        for entry in readlist:
            if(line[:(entry.len() + 2)] == entry):
                returnslist[entry] = line[(entry.len() + 2):]
目前我使用的笔记本电脑不能使用Python,所以我正在开发一个不能使用文件的在线IDE。这样行吗?我希望该文件像配置文件一样工作。例如:

Int1: 2
Int2: 12
Int3: 32
Int4: 65
Str1: Lol
Bool1: True
我的代码应该成为字典:

{"Int1": "2", "Int2": "12", "Int3": "32", "Int4": "65", "Str1": "Lol", "Bool1": "True"}

有没有更干净的方法?我想不出有什么。您还可以看到其中的错误吗?

您可以使用文件格式生成一个简短的最小字符串,并使用io.StringIO模拟文件以查看代码的工作情况。如果你想在一个在线ide上使用文件,如果你需要像“配置文件”这样的东西,那么最好使用
pickle
YAML
JSON
。如果你的文件中有
Int1:2
,那么读一行,用
“Int1:2”来拆分它。拆分(':')
,然后你会得到两个字符串
Int1
2
(对于空格,请使用
strip()
),然后您可以检查readlist中的
是否为“Int1”
import yaml

my_data = """
    Int1: 2
    Int2: 12
    Int3: 32
    Int4: 65
    Str1: Lol
    Bool1: True
"""

data_dict = yaml.load(my_data)