[英]Read data from columns in .xlsx and save each one as seperate .txt file with python
I need to make a script in python to read one column at a time from .xlsx file and save data from each in new .txt file with conecutive names like (file1.txt, file2.txt...) I alredy have some parts of script, but am unable to combine them.我需要在 python 中制作一个脚本,一次从 .xlsx 文件中读取一列,并将每个数据保存在新的 .txt 文件中,并使用连续的名称,如 (file1.txt, file2.txt...) 我已经有一些部分脚本,但我无法将它们组合起来。
part of script for selecting data:用于选择数据的脚本的一部分:
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'))
for naming file:命名文件:
while i:
i+=1
try:
with open('output{}.txt'.format(i), 'x'):
break
except PermissionError:
continue
SOLVED:解决了:
this script works.这个脚本有效。 The key is indenting second for statement
关键是缩进第二个语句
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.