我已经找到了答案,我想要的只是它看到(如果description
中的readline
)将数据写入活动单元格所在的下一列,而不是下一行。
以下是我已经获得的样本:
This is what I want
This is the current data
row = 1
while True:
result = crt.Screen.WaitForStrings( waitStrs )
if result == 2:
break
screenrow = crt.Screen.CurrentRow - 1
readline = crt.Screen.Get(screenrow, 1, screenrow, 80)
items = readline.split(':')
# Split the line ( ":" delimited) and put some fields into Excel
if 'interface ' in readline:
worksheet.writerow(items[:1])
++row
elif ' description' in readline \
or ' ip address' in readline \
or ' port allow' in readline \
or 'binding' in readline:
worksheet.writerow(items[:1]) # <--(write this data in the next column where the active cell is)
示例数据:
Info
interface Aux0/0/1
inferface Vlanif30
description Publc Link to CX600-3-B
ip address 10.132.10.132 255.255.255.252
答案 0 :(得分:1)
使用下面给出的示例数据我的代码段应该可以胜任。有关进一步说明,请参阅代码中的注释。可以找到Python的csv模块的文档here。
示例数据:
Info
interface Aux0/0/1
inferface Vlanif30
description Public Link to CX600-3-B
ip address 10.132.10.132 255.255.255.252
代码:
#!/usr/bin/env python3
# coding: utf-8
import csv
description_index = None
before_description = []
after_description = []
# Open input file and read each line
with open('data.csv') as infile:
lines = infile.read().splitlines()
# Iterate through read lines and look for ' description'
# since we need to split output format based on this line number
for lno, line in enumerate(lines):
if ' description' in line:
description_index = lno
# if there is no ' description' we do not want to change output format
# and write all data to a row each.
# In order to do so, we set description_index to the length of the lines list.
if not description_index:
description_index = len(lines)
# Knowing the line number of ' description' gives us the
# possibility to divide lines into two parts
before_description = lines[:description_index]
after_description = lines[description_index:]
# Open output file, init a csvwriter and write data.
# Since a row is defined by a list passed to the writer
# we iterate through the lines before the ' description'
# and cast each element as a list before passing it to the csvwriter.
# Since the part after ' description' should be in one row we write all
# all elements to a single list.
# Since we do not want to write empty lines, we check if each element exists.
with open('output.csv', 'w', newline='') as outfile:
outputwriter = csv.writer(outfile)
for element in before_description:
if element:
outputwriter.writerow([element])
outputwriter.writerow([element for element in after_description if element])
输出(以逗号分隔的csv文件):
Info
interface Aux0/0/1
inferface Vlanif30
description Public Link to CX600-3-B, ip address 10.132.10.132 255.255.255.252