【问题标题】:Pandas python multiple export read text filesPandas python 多次导出读取文本文件
【发布时间】:2021-03-18 12:52:02
【问题描述】:

Helo 任何人都可以帮助我读取和导出多个文件。我有客户数据的每日档案。如何自动读取所有文件:

import pandas
with open("Customers_1oct.txt", "r") as file:
    data = file.read()

df = pandas.DataFrame(
    [
        {
            "Detail Indicator": line[0:2].strip(),
            "Name": line[2:102].strip(),
            "Ref No": line[182:232].strip(),
            "Ind": line[232:234].strip(),
            "Amount": line[234:249].strip(),
         
        }
        for line in data.splitlines()
        if len(line) > 1
    ]
)
df

我也想导出成多个文件,怎么办?

datatoexcel = pandas.ExcelWriter('1oct.xlsx') 
  

df.to_excel(datatoexcel) 
  

print('DataFrame is written to Excel File successfully.')

【问题讨论】:

  • 您想以哪种方式导出到多个文件中?

标签: python pandas numpy operating-system glob


【解决方案1】:
  1. 将当前代码封装在一个函数中。
  2. 使用例如glob 检索文件列表。
  3. 使用for 循环为每个文件调用您的函数。

例子:

from glob import glob

def process(filename):
    print("Processing file %s..." % filename)

for item in glob("*.txt"):
    process(item)
$ ls
script.py  test1.txt  test2.txt  test3.txt  test4.txt
$ python3 script.py
Processing file test1.txt...
Processing file test4.txt...
Processing file test2.txt...
Processing file test3.txt...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 2017-07-27
    • 2020-07-10
    • 2021-12-22
    相关资源
    最近更新 更多