![](/img/trans.png)
[英]Python Pandas: Skip if there is no data then continue writing into excel
[英]Writing data into an Excel spreadsheet - why does it skip every second line?
我在Python中使用openpyxl將一些數據從txt文件復制到Excel電子表格中。 以下代碼盡管簡單,卻跳過了第二行,僅寫入電子表格中的其他每一行。 有人可以幫忙告訴我我在做什么錯嗎?
line_index = 1 # To keep track of the current line's "index" in the file
for l in f:
line = l.split(",")
# Transfer needed values into Spreadsheet, leaving the first two columns
# empty so they can be populated later, because openpyxl doesn't support
# easy insertion of columns.
for i in range(len(line)):
ws.cell(row=line_index, column=i+3).value = line[i]
line_index += 1
首先,如果需要計數器,請使用enumerate()
函數以提高可靠性。 其次,不用調用ws.cell()
而是在行之前添加兩個空值[None]*2
以便可以使用ws.append()
。 第三,openpyxl v2.5確實支持列和行的插入和刪除。
TWO_COLS = [None] * 2
for line in f:
line = TWO_COLS + line.split()
ws.append(line)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.