[英]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.