![](/img/trans.png)
[英]Python: How do you read a specific line from a text file based on the previous line?
[英]How do you read a text file into a dictionary with the information on one line separated by '\t' python
我的文本文件如下所示: CSCI 160:4 CSCI 289:3 EE 201:4 MATH 208:3
(全部在一行中,由制表符'\t'
分隔)。 我如何将该文本文件读入字典(key,val)以':'
分隔
尝试:
s = "CSCI 160:4\tCSCI 289:3\tEE 201:4\tMATH 208:3"
d = dict(item.split(":") for item in s.split("\t"))
print(d)
印刷:
{"CSCI 160": "4", "CSCI 289": "3", "EE 201": "4", "MATH 208": "3"}
编辑:要从文件中读取,您可以使用此示例(假设您的文件只有一行):
with open("your_file.txt", "r") as f_in:
s = f_in.read().strip()
d = dict(item.split(":") for item in s.split("\t"))
print(d)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.