Skip to main content
 首页 » 编程设计

Python 将 XLSX 保存为 CSV

2024年10月01日6dudu

我不是 python 用户。但是,我厌倦了手动将 Excel 文件保存为 CSV,而且这家店里的每个人都讨厌 Perl。我无法让 Spreadsheet::XLSX 在此工作环境中工作。他们只使用 Python。

python版本是2.4

 #!/usr/bin/python 
 
import openpyxl 
import csv 
 
wb = openpyxl.load_workbook('DailySnapshot.xlsx') 
sh = wb.get_active_sheet() 
with open('test.csv', 'wb') as f: 
    c = csv.writer(f) 
    for r in sh.rows: 
        c.writerow([cell.value for cell in r]) 

DailySnapshot.xlxs 保存在与脚本相同的目录中。这是一个单页的 Excel 电子表格,工作表名为 'Table1'。我想我会将 CSV 文件命名为 test.csv。这是它抛出的错误。

File "./secondPyTry.py", line 8 with open('test.csv', 'wb') as f: ^ SyntaxError: invalid syntax

请您参考如下方法:

正如评论中所说,Python 2.4 不支持with。您应该像这样打开文件:

f = open('test.csv', 'wb') 
c = csv.writer(f) 
for r in sh.rows: 
    c.writerow([cell.value for cell in r]) 
f.close()