Python 每次只读一行,带或不带“"\";最后
我有一个文件是这样填写的:Python 每次只读一行,带或不带“"\";最后,python,file,Python,File,我有一个文件是这样填写的: Samsung CLP 680/ CLX6260 + CLT-C506S/ELS + CLT-M506S/ELS + CLT-Y506S/ELS + 39.50 Xerox Phaser 6000/6010/6015 + 106R01627 + 106R01628 + 106R01629 + 8.43 Xerox DocuPrint 6110/6110mfp + 106R01206 + 106R01204 + 106R01205 + 7.60 Xerox Phaser
Samsung CLP 680/ CLX6260 + CLT-C506S/ELS + CLT-M506S/ELS + CLT-Y506S/ELS + 39.50
Xerox Phaser 6000/6010/6015 + 106R01627 + 106R01628 + 106R01629 + 8.43
Xerox DocuPrint 6110/6110mfp + 106R01206 + 106R01204 + 106R01205 + 7.60
Xerox Phaser 6121/6121D + 106R01466 + 106R01467 + 106R01468 + 18.20
当我读到它时:
for line in excelRead:
title=line.split("+")
title=[lines.strip()for lines in title]
有时在行的末尾有一个“\n”,有时没有,如果行以\n spliting结尾,则会给我5个元素,如果不是9,等等,直到它找到为止,我猜是“\n”
因此,问题是:如何每次只读取文件中的一行,并每次获取5个元素,结尾是否有“\n”?我无法检查所有文件的结尾是否有“\n”
谢谢
最好避免让一个变量(title
)表示两种不同的含义。我没有在你的第二行中给它一个不同的名字,而是完全删除了这一行,并将拆分
放在列表中
<> >而不是将代码> >行<代码>到<代码>分割<代码>中,首先我是<代码> \n>代码>(从结尾删除那个字符)您可以考虑使用CSV模块来解析这个,并通过模型放置到DICT中:
import csv
data={}
with open('/tmp/excel.csv') as f:
for line in csv.reader(f, delimiter='+', skipinitialspace=True):
data[line[0].strip()]=[e.strip() for e in line[1:]]
print data
# {'Samsung CLP 680/ CLX6260': ['CLT-C506S/ELS', 'CLT-M506S/ELS', 'CLT-Y506S/ELS', '39.50'],
'Xerox Phaser 6121/6121D': ['106R01466', '106R01467', '106R01468', '18.20'],
'Xerox DocuPrint 6110/6110mfp': ['106R01206', '106R01204', '106R01205', '7.60'],
'Xerox Phaser 6000/6010/6015': ['106R01627', '106R01628', '106R01629', '8.43']}
缺少\n时,这将拆分标题[4]以提供两个标题:
import re
data = []
with open('aa.txt') as excelRead:
for line in excelRead:
title=line.split("+")
title=[lines.strip()for lines in title]
while len(title) > 5:
one = re.sub('(\d+\.\d+)', '', title[4])
five = title[4].replace(one, '')
title1 = title[:4] + [five]
title = [one] + title[5:]
data.append(title1)
data.append(title)
for item in data:
print(item)
您可以轻松地将数据设置为字典而不是列表。当缺少\n项时,第5项是否与“8.43Xerox DocuPrint 6110/6110mfp”类似?因此,当我尝试按照您所说的方式执行时,它会给我数据[line[0].strip()]=[e.strip()对于[1:]行中的e]类型错误:列表索引必须是整数,而不是str[在0.0s中完成,退出代码为1]为什么?
import re
data = []
with open('aa.txt') as excelRead:
for line in excelRead:
title=line.split("+")
title=[lines.strip()for lines in title]
while len(title) > 5:
one = re.sub('(\d+\.\d+)', '', title[4])
five = title[4].replace(one, '')
title1 = title[:4] + [five]
title = [one] + title[5:]
data.append(title1)
data.append(title)
for item in data:
print(item)