因此,我应该将其传输到电话簿字典中的文件文本如下所示:
名字 1 名字 2 数字
名字3 名字4 数字2
等等..
我尝试过的:
def read():
file1=open("file.txt","r")
dict={}
for line in file1:
line=line.split()
if not line:continue
dict[line[0]]=line[1:]
print(dict)
当我运行它时,它什么都不打印。
谢谢!
请您参考如下方法:
这是我的方式
def read_dict():
file1 = open("file.txt", 'r')
dict={}
# read lines of all
lines = file1.readlines()
# Process one line at a time.
for line in lines:
line = line.split()
if not line: continue
dict[line[0]] = line[1:]
file1.close()
print(dict)
读字典()
或者 (与)一起使用 你不必关闭文件
def read_dict():
with open("file.txt", 'r') as file1:
dict={}
# read lines of all
lines = file1.readlines()
# Process one line at a time.
for line in lines:
line = line.split()
if not line: continue
dict[line[0]] = line[1:]
print(dict)
