简体   繁体   English

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

[英]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.

相关问题 读取csv行并将其另存为单独的txt文件,命名为行-python - Read csv lines and save it as seperate txt file, named as a line - python 使用 python 代码从文件 txt 读取数据并将其保存在列表中 - Read and save data from file txt in a list with python code 读取多个txt文件,然后将每个文件另存为具有相同标题的xlsx文件 - read multiple txt files then save each as xlsx file with same header for each 从每张 .xlsx 文件中读取特定列 - Read Specific Columns From Each Sheet of .xlsx File 读取每个 url 并将其保存到单独的 pdf Python - Read each url and save it to seperate pdf Python Python Pandas从一列中读取csv,然后将各列分开 - Python pandas read a csv from one column then seperate columns 如何使用 Python 将数据从 txt 文件复制并粘贴到 XLSX 作为值? - How to copy data from txt file and paste to XLSX as value with Python? 如何让python读取txt文件中的每一行并制作单独的列表? - How can I get python to read each line in a txt file and make seperate lists? Python 请求:从一个 TXT 文件中获取所有行,一次获取一个请求并将它们保存到一个新的 TXT 文件中 - Python Requests: take all lines from a TXT file, one at a time to get requests from each and save them to a new TXT file 使用 python 将 .xlsx 转换为 .txt? 或格式化 .txt 文件以修复列缩进? - Convert .xlsx to .txt with python? or format .txt file to fix columns indentation?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM