# coding=utf-8
import re
import json
def txtToJson():
path = "port_result.txt"
with open(path,'r', encoding="utf-8") as file:
seq = re.compile(":")
result = []
for line in file:
lst = seq.split(line.strip())
item = {
"name": lst[0]
}
result.append(item)
print(type(result))
with open('txtToJson.json', 'w') as dump_f:
json.dump(result,dump_f)
if __name__ == '__main__':
txtToJson()
Traceback (most recent call last):
File "<pyshell#73>", line 2, in <module>
txtToJson()
File "<pyshell#71>", line 3, in txtToJson
with open(path,'r', encoding="utf-8") as file:
FileNotFoundError: [Errno 2] No such file or directory: 'port_result.txt'
你这第一步就报错了,txt文件不存在
你把这文件放哪了,是跟py文件放一起了吗,如果不在一起,要把路径带上啊,要不然你让程序上哪去找
另,你的逻辑也有问题
你把txt文件的每一行都转一次json,然后存文件
文件用的是'w',也就是每次都覆盖写入
那如果你的文件有100行,只有第100行的数据会写入文件,前99行都被覆盖了