繁体   English   中英

Python设置输出文件为空

[英]Python set output file is empty

我正在编写一个Python脚本来读取文件,逐行读取该文件,并通过用户命令行参数将数据从该文件解析到另一个文本文件。 现在,我能够逐行读取输入文件,并通过命令行参数解析出数据。 但是,我尝试写入的输出文件为空(它不满足我要解析的数据)。

temp.log包含:

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()

output_file = open ('output.txt', 'w')

data = []
for line in lines:
   date = re.match(r'\d{2} \w+ \d{2}', line).group()    
   time = line.split()[3]
   ids = line.split()[4]
   row = [date, time, ids]

   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:'

  data.append(row)
  output_file.writelines(row)

  for row in data:
  print(row)

  output_file.close()

我期望将输出写入到名为“ output.txt”的文件中,但是该文件不是由代码生成的。

因此,用户将运行命令行参数python export.py date agent,并且我期望output.txt文件具有日期和代理列表,但它为空

您缺少写入文件的信息。 尝试添加与此类似的内容,而不是最后三行:

with open('output.txt', mode='wt', encoding='utf-8') as f:
    f.writelines(row)

您一开始就做对了,但最后却没有再做。 当您要访问文件时,必须首先open它,但最后没有这样做。

因此,您应该将最后三行更改为类似

f = open(filename, mode) # mode probably "w" or "a"
f.writelines(pieces_of_data)
f.close()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM