繁体   English   中英

从 .xlsx 中的列中读取数据并使用 python 将每个数据保存为单独的 .txt 文件

[英]Read data from columns in .xlsx and save each one as seperate .txt file with python

我需要在 python 中制作一个脚本,一次从 .xlsx 文件中读取一列,并将每个数据保存在新的 .txt 文件中,并使用连续的名称,如 (file1.txt, file2.txt...) 我已经有一些部分脚本,但我无法将它们组合起来。

用于选择数据的脚本的一部分:

for i in range(1, m_row + 1):
    cell_obj = sheet_obj.cell(row=i, column=j+1)
    print(cell_obj.value)
    print(cell_obj.value, file=open(
        file.txt',
        'a'))

命名文件:

while i: 
    i+=1
    try:
        with open('output{}.txt'.format(i), 'x'): 
    break
    except PermissionError:
        continue

解决了:

这个脚本有效。 关键是缩进第二个语句

import openpyxl
path = "input.xlsm"
wb_obj = openpyxl.load_workbook(path)
sheet_obj = wb_obj.active
m_row = sheet_obj.max_row
m_col = sheet_obj.max_column

for j in range(1, m_col + 1):
    name = sheet_obj.cell(row=2200, column=j).value
    outputFile = open(r'file.{}.txt'.format(name), 'w')
    for i in range(1, m_row + 1):
        cell_obj = sheet_obj.cell(row=i, column=j)
        print(cell_obj.value, file=outputFile)
    outputFile.close()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM