Py学习  »  Python

在python中连接数据excel数据的循环文件名?

user8261831 • 5 年前 • 1745 次点击  

我有一些加入excel文件的代码,如何编辑我的代码,使我不必每次都键入完整的文件名?

谢谢

代码如下:

import pandas as pd

excel_names = ["Market_Information_System_Control_daily_trading_day_170701.xlsx",
               "Market_Information_System_Control_daily_trading_day_170702.xlsx",
               "Market_Information_System_Control_daily_trading_day_170703.xlsx",
               "Market_Information_System_Control_daily_trading_day_170704.xlsx",
               "Market_Information_System_Control_daily_trading_day_170731.xlsx"]

excels = [pd.ExcelFile(name) for name in excel_names]
frames = [x.parse(x.sheet_names[1], header=None,index_col=None) for x in excels]

frames[1:] = [df[1:] for df in frames[1:]]
combined = pd.concat(frames)
combined.to_excel("c.xlsx", header=False, index=False)

Eddi1: image

我只是不想有时间流动,没有航向休息。

我想这和这个有关: frames[1:] = [df[1:] for df in frames[1:]]

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/40908
 
1745 次点击  
文章 [ 2 ]  |  最新文章 5 年前
Prune
Reply   •   1 楼
Prune    6 年前

像这样的?将一致部分放入静态变量中;将变量部分放入列表中。建立另一个列表理解。

prefix = "Market_Information_System_Control_daily_trading_day_"
ext = ".xlsx"
dates  = ["170701",
          "170702",
          "170703",
          "170704",
          "170731"]
excel_names = [prefix + day + ext for day in dates]

print(excel_names)

结果:

['Market_Information_System_Control_daily_trading_day_170701.xlsx',
 'Market_Information_System_Control_daily_trading_day_170702.xlsx',
 'Market_Information_System_Control_daily_trading_day_170703.xlsx',
 'Market_Information_System_Control_daily_trading_day_170704.xlsx',
 'Market_Information_System_Control_daily_trading_day_170731.xlsx']
Dora
Reply   •   2 楼
Dora    6 年前

这就是你要找的吗?它将打印出所有文件名,您只需循环遍历这些文件名,然后组合

from os import listdir
from os.path import isfile, join

folder_path = './'

onlyfiles = [f for f in listdir(folder_path) if isfile(join(folder_path, f))]
print(onlyfiles);

P.S.这是从 How do I list all files of a directory?

编辑,如果你真的想做某种文件扩展名过滤,我使用 json 以文件为例,根据需要进行更改

from os import listdir
from os.path import isfile, join

folder_path = './'

onlyfiles = [f for f in listdir(folder_path) if isfile(join(folder_path, f))]
filter_extension = []
my_ext = 'json'

for f in listdir(folder_path):
    extension = f.split('.')[-1]
    if (extension == my_ext):
        filter_extension.extend([f])

print(filter_extension)