如何在python中逐行读取文件

2024-09-30 20:21:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图阅读下面的python文本文件,我很难在输出中获得关键字值,但它没有按预期工作:

你知道吗测试.txt你知道吗

productId1 ProdName1,ProdPrice1,ProdDescription1,ProdDate1
productId2 ProdName2,ProdPrice2,ProdDescription2,ProdDate2
productId3 ProdName3,ProdPrice3,ProdDescription3,ProdDate3
productId4 ProdName4,ProdPrice4,ProdDescription4,ProdDate4

你知道吗我的Python.py你知道吗

import sys
with open('test.txt') as f
  lines = list(line.split(' ',1) for line in f)
  for k,v in lines.items();
     print("Key : {0}, Value: {1}".format(k,v))

我试图解析文本文件,并试图分别打印键和值。看来我做错什么了。需要帮忙吗?你知道吗

谢谢!你知道吗


Tags: intxtforline关键字lines文本文件productid2
3条回答

你在不必要地存储一个列表。你知道吗

循环、拆分和打印

with open('test.txt') as f:
    for line in f:
        k, v = line.rstrip().split(' ',1) 
        print("Key : {0}, Value: {1}".format(k,v))

这应该是可行的,有一个列表:

with open('test.txt') as f:
    lines = [line.split(' ',1) for line in f]
    for k, v in lines:
        print("Key: {0}, Value: {1}".format(k, v))

你可以用一个dict comp在bat的右边做一个dict,然后迭代这个列表来打印你想要的内容。您所做的是创建一个没有items()方法的列表。你知道吗

with open('notepad.txt') as f:
    d = {line.split(' ')[0]:line.split(' ')[1] for line in f}
    for k,v in d.items():
        print("Key : {0}, Value: {1}".format(k,v))

相关问题 更多 >