python - 如何从Excel中读取数据并将其逐行写入文本文件?

标签 python xlrd

我想编写代码从 Excel 中获取数据并将其写入文本文件。这是我的代码:

import xlrd
import os.path
wb = xlrd.open_workbook(os.path.join('D:\TRB 2014 Data','SPS1 demo data.xlsx'))
wb.sheet_names()
sh = wb.sheet_by_index(0)
i = 1

while sh.cell(i,11).value != 0:

   Load = sh.cell(i,11).value
   D1 = sh.cell(i,13).value
   D2 = sh.cell(i,14).value
   D3 = sh.cell(i,15).value
   D4 = sh.cell(i,16).value
   D5 = sh.cell(i,17).value
   D6 = sh.cell(i,18).value
   D7 = sh.cell(i,19).value
   DB1 = str(Load) + "  " + str(D1) + "  " + str(D2) + "  " + str(D3)+ "  " + str(D4)+ "  " + str(D5)+ "  " + str(D6)+ "  " + str(D7)

   file = open("Output.txt", "w")
   file.write(DB1 + '\n')
   file.close
   i = i + 1

这段代码的问题是写入文本文件的数据总是显示在第一行。因此,虽然我在 excel 中有 20 行数据,但文本文件仅在文本文件的第一行显示 excel 文件中的最后数据。我在 file.write 中有 '\n' 但是,它似乎不起作用。

最佳答案

你应该 open具有附加模式output.txt文件:

file = open("Output.txt", "a")

此外,您应该在进入循环之前执行此操作,并且在该循环之后应将其关闭。


更新:

在这种情况下,您可以使用 with 而不是在最后关闭文件句柄。

还包括@Josh in his own answer提出的好建议,代码可能是这样的:

import xlrd
import os.path

wb = xlrd.open_workbook(os.path.join('D:\TRB 2014 Data','SPS1 demo data.xlsx'))
wb.sheet_names()
sh = wb.sheet_by_index(0)
i = 1
with open("Output.txt", "a") as my_file:
    while sh.cell(i,11).value != 0:
        Load = sh.cell(i,11).value
        all_d = sh.col_values(i, 13, 19)
        DB1 = Load + " " + (" ".join(all_d))
        my_file.write(DB1 + '\n')
        i += 1

关于python - 如何从Excel中读取数据并将其逐行写入文本文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17977584/

相关文章:

python - 如何在整个工作簿中保留公式

python - 在Python xlrd中读取Excel文件

python - 在python中下载和使用xls文件时出现问题

python xlrd读取xls文件,路径前面的r是做什么用的?

python - 如何让爬虫在 cron 作业上运行?

Python/Webdriver 检查选择选项被禁用

Python:从方程结果创建嵌套列表

python xlrd 格式不受支持,或文件损坏。

python - while 循环计数器比较两个列表

python - 存储 GNU 时间命令和脚本的输出