gpt4 book ai didi

python - 如何修复输出文件不逐行中断输出?

转载 作者:太空宇宙 更新时间:2023-11-04 01:58:45 25 4
gpt4 key购买 nike

我正在编写一个 Python 脚本来读入一个文件,逐行读取该文件并通过用户命令行参数将数据从该文件解析到另一个文本文件。现在,我能够逐行读取输入文件并通过命令行参数解析数据。但是,我尝试编写的输出文件在一行中打印所有内容,而不是逐行打断输出。

临时日志:

06 May 19 03:40:35 3 abCodeClearTrap Error Clear Trap (agent: 12367a12,
chassis:12367a12, ErrIdText: ERROR ID TEXT, csssi: EXTIFG, clearedID:
0x089088394)

06 May 19 03:44:35 3 abCodeErrorTrap Error Trap (agent: 12368a15, chassis:
12368a15, ErrIdText: Skip this item, csssi: SSRSSR, clearedID:
0x089088394)

我的代码:

import re, sys

with open('temp.log') as f:
lines = f.readlines()

with open('output.txt') as o:

data = []
for line in lines:
if 'date' in sys.argv:
try:
date = re.match(r'\date{2} \w+ \date{2}', line).group()
row.append(date)
except:
date = 'date'
if 'agent' in sys.argv:
try:
agent = re.search(r'agent:\s(.*?),', line).group()
row.append(agent)
except:
agent = 'agent:'
if 'err' in sys.argv:
try:
errID = re.search(r'ErrIdText:\s(.*?),', line).group()
row.append(errID)
except:
errID = 'ErrIdText:'
if 'clear' in sys.argv:
try:
clear = re.search(r'clearedID:\s(.*?)\)', line).group()
row.append(clear)
except:
clear = 'clearedID:'

row = []
data.append(row)

for row in data:
lines = o.writelines(row)
print(row)

o.close()

没有错误消息,但我希望我的 output.txt 文件逐行分解。

例如:如果用户运行:

python export.py agent chassis

我希望打印 output.txt

['agent: 12367a12,', 'chassis:12367a12,']
['agent: 12368a15,', 'chassis:12368a15,']

但是output.txt中的输出是:

agent:12367a12, chassis:12367a12, agent:12368a15, chassis:12368a15,

最佳答案

给你:)

for row in data:
lines = o.writelines(row)
lines = o.writelines("\n")
print(row)

for row in data:
row.append("\n")
lines = o.writelines(row)
print(row)

顺便说一句,我很惊讶这段代码能正常工作......因为你在使用它之后定义了行

   // ( * )
if something
try:
date = re.match(r'\date{2} \w+ \date{2}', line).group()
row.append(date) // should crash
except:
date = 'date'
if 'agent' in sys.argv:
try:
agent = re.search(r'agent:\s(.*?),', line).group()
row.append(agent) // should crash
except:
agent = 'agent:'
if 'err' in sys.argv:
try:
errID = re.search(r'ErrIdText:\s(.*?),', line).group()
row.append(errID) // should crash
except:
errID = 'ErrIdText:'
if 'clear' in sys.argv:
try:
clear = re.search(r'clearedID:\s(.*?)\)', line).group()
row.append(clear) // should crash
except:
clear = 'clearedID:'

row = [] // this should be defined where I put the star ( * )
data.append(row) // always appends empty row ( [] )

关于python - 如何修复输出文件不逐行中断输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56194750/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com