[英]Reading txt file line by line and field by field
我正在努力阅读附加的 TXT 文件以将每个从文件中读取的字段呈现为 csv 我制作了一个接近我想要的代码但我不前进。
TXT 文件格式:
COMPANY TEST OF BRAZIL- Junho/2022 Horista
37-6 WALTER WHITE DA SILVA
1006136-9 MOTORISTA A33 1 00011523
001 Hrs Normais Diurnas 183,333 2.555,66 +
031 Hrs Dsr Vencimento 36,667 511,14 +
037 Dsr Adicionais 306,36 +
053 Reembolso de Vale Transpo 47,61 +
102 Hrs Extras ( 60%) 68,680 1.531,84 +
824 Vale Transporte 500,00 +
290 Alimentacao Funcionario 10,50 -
404 Adiantamento Normal Desco 1.011,95 -
476 Desconto Seconci Dependen 65,46 -
511 Inss Normal 522,87 -
561 Irf Normal 90,07 -
567 Irf Recol Adto 214,77 -
820 Desc de Vale Transporte 184,00 -
5.452,61+ 2.099,62-
3.352,99
13,94 4.905,00 4.905,00 392,40 2.965,82
COMPANY TEST OF BRAZIL- Junho/2022 Horista
102-0 WILTON PEATER TEMPLATE
31022-0 L EQUIPE B 000 1 00011524
001 Hrs Normais Diurnas 183,333 2.220,16 +
031 Hrs Dsr Vencimento 36,667 444,04 +
037 Dsr Adicionais 225,77 +
053 Reembolso de Vale Transpo 26,40 +
102 Hrs Extras ( 60%) 58,260 1.128,85 +
290 Alimentacao Funcionario 10,50 -
404 Adiantamento Normal Desco 854,04 -
476 Desconto Seconci Dependen 98,19 -
511 Inss Normal 398,81 -
561 Irf Normal 48,77 -
567 Irf Recol Adto 211,64 -
820 Desc de Vale Transporte 159,85 -
4.045,22+ 1.781,80-
2.263,42
12,11 4.018,82 4.018,82 321,50 2.554,33
我的代码读取了我想要的位置的第一行,但下面的行我不能,更不用说在文件中包含的下一张工资单上重复读取了。
# Read TXT
with open ("I:input\\test.txt", "r") as ft:
head_text = ft.readline()
# Capturar campos
## Head
competence = head_text[46:59]
company = head_text[:45]
print('competence',';','company')
print(competence,';',company,)
目前的输出是这样的:
# competence;company
junho/2022; COMPANY TEST OF BRAZIL
出口应该如何
# competence;company;id_employee;employe;etc...
junho/2022;COMPANY TEST OF BRAZIL;37-6;WALTER WHITE DA SILVA...
junho/2022;COMPANY TEST OF BRAZIL;102-0;WILTON PEATER TEMPLATE...
逐行读取和捕获数据我必须完成一个工资单,该工资单将在输出中形成一行,第二个工资单将在输出中形成第二行,因此它将一直到 txt 文件的末尾此刻我无法前进,我迷路了。
我认为您可以使用以下代码来获得所需的输出。 您应该确保您的第一个数据是否具有类似的模板。 如果需要编辑所需的输出,您也可以编辑模板。 请看代码:
!pip install ttp
from ttp import ttp
import json
with open ("test.txt", "r") as ft:
data_to_parse = ft.read()
ttp_template = """
{{Part_2|ORPHRASE}}- {{Part_1}} {{ignore}}
{{Part_3}} {{Part_4|ORPHRASE}}
"""
def stack_test(data_to_parse):
parser = ttp(data=data_to_parse, template=ttp_template)
parser.parse()
# print result in JSON format
results = parser.result(format='json')[0]
#print(results)
#converting str to json.
result = json.loads(results)
return(result)
# print(stack_test(data_to_parse))
for i in stack_test(data_to_parse)[0]:
print(f"{i['Part_1']};{i['Part_2']};{i['Part_3']};{i['Part_4']}")
首先查看print(i)
输出:
另请参阅您想要的输出:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.