【问题标题】:python read excel file and save N txt files with title and content from excelpython读取excel文件并保存N个txt文件,其中包含excel的标题和内容
【发布时间】:2020-01-09 22:35:15
【问题描述】:

我有 3 列的 excel 文件:

 index  |   name  | surname
 0      |   John  | White
 2      |   Bill  | Black
 3      |   Jack  | Red

我需要创建 N 个 txt 文件(基于行数),其标题在名称列中,内容在姓氏列中。

例如,基于上面的示例,我想要 3 个文件,John.txt(内容为“白色”)、Bill.txt(内容为黑色)和 Jack.txt(内容为红色)

【问题讨论】:

  • 你能贴出你试图解决这个问题的代码吗?

标签: python loops file


【解决方案1】:

您可以使用 pandas 并将值提取为列表来完成此操作

# import and read
import pandas as pd
df = pd.read_excel("your_file.xlsx")

# create lists
names = df["name"].values
file_contents = df["surname"].values

# iterate through lists
for name, content in zip(names, file_contents): 
    f = open(f"{name}.txt", "w")
    f.write(content)

【讨论】:

    【解决方案2】:

    您可以使用 pylightxl 轻松完成此操作,请参阅 https://pylightxl.readthedocs.io/en/latest/quickstart.html

    import pylightxl as xl
    
    workbook = xl.readxl('yourexcefile.xlsx')
    
    for row in workbook.ws('Sheet1').rows:
        filename = row[2]
        text = row[3]
        with open(filename, "w") as f:
            f.write(text)
    

    【讨论】:

      猜你喜欢
      • 2022-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-11
      • 1970-01-01
      • 1970-01-01
      • 2023-01-11
      • 2019-04-06
      相关资源
      最近更新 更多