for循环多个值

时间:2018-11-13 05:25:17

标签: python python-3.x for-loop xlsxwriter

我的脚本在下面:

import xlsxwriter
import subprocess

workbook = xlsxwriter.Workbook('demo.xlsx')
worksheet = workbook.add_worksheet('NMOC')
bold = workbook.add_format({'bold': True})

 # Write some data headers.
worksheet.write('A1', 'RNC', bold)
worksheet.write('B1', 'CELL', bold)
for line in open('/root/Desktop/Scripting/Update_Table/eaw/test.txt'):

alias = line.rstrip("\n").split(';')
print(alias)

# Start from the first cell. Rows and columns are zero indexed.
row = 1
col = 0

for rnc, cell in (alist):
   worksheet.write(row,col,  rnc)
   worksheet.write(row,col + 1, cell)
   row += 1
workbook.close()

我正在使用python 3.5版本。这是我得到的错误:

['BSC19', 'TS9001']
['BSC19', 'TS555']
Traceback (most recent call last):
  File "test.py", line 53, in <module>
    for rnc, cell in (alias):
ValueError: too many values to unpack (expected 2)

我的代码有什么问题?

[root @ nocjobs eaw]#cat test.txt

BSC19;TS9001
BSC19;TS555

2 个答案:

答案 0 :(得分:1)

我敢打赌问题出在这里-> for rnc, cell in (alist):

因为在某些迭代(甚至可能是第一个迭代)中,变量alist仅包含一个值,但是您尝试将其解压缩为tuple(rnc, cell)

据我了解,您想要执行以下操作:

row = 1
for line in open('test.txt'):
    alist = line.rstrip("\n").split(';')
    col = 0
    for value in (alist):
        worksheet.write(row, col, value)
        col += 1
    row += 1

答案 1 :(得分:1)

如果您要在问题中使用line = "cat myfile BSC19;TS9001 BSC19;TS555",那么问题就出在alist里面是什么,['cat myfile BSC19', 'TS9001 BSC19', 'TS555']是3项清单。

for rnc, cell in (alist):就像赋值rnc, cell = alist,这意味着它期望alist恰好有两件事。

我相信您需要修复line.rstrip( ).split(';'),但是我不确定testtt.sh文件中数据的预期格式是什么。