如何实现改变文件名读取的迭代方式,以及如何将结果组合到单个excel文件中



我是python的新手。有一项任务,必须为所有excel文件(1.xlsx-350.xlsx(找到以下内容,大约350个excel文件包含在一个文件夹中(视频(。并编写了以下代码,它运行良好,但很耗时,每次迭代都必须手动更改文件名。即使在这个过程的最后,我也必须将所有350个excel文件操作的数据组合成一个excel文件。但在我的代码中,它覆盖了每一次迭代。请帮我解决这个问题。

data12 = pd.read_excel (r'C:UsersVideos1.xlsx')
gxt = data12.iloc [:,0]
gyan = data12.iloc [:,1]
int= gyan.iloc[98:197]
comp= gyan.iloc[197:252]
seg= gyan.iloc[252:319]
A= max(int)   
B= max(comp)  
C= min(comp)  
D= max(seg) 
s = pd.Series([A, B, C, D])
frame_data= [gyan, comp, seg, stat]
result = pd.concat(frame_data)
result.to_excel("output.xlsx", sheet_name='modify_data', index=False) 

谢谢你的帮助。

请检查以下代码:

import pandas as pd
import numpy as np
import openpyxl
from openpyxl import load_workbook, Workbook
import os
# Give an excel filename and worksheet name 
output='C:UsersVideosoutput.xlsx'
worksheet = 'Sheet'
wb = Workbook() 
# If file not present at location, then create one
if os.path.isfile(output):
print('File Present')
else:
print('Creatted New file')
ws = wb.create_sheet(worksheet)
wb.save(output)
# Loop for all 350 files
for i in range(1, 351):
print('File {}:'.format(i))
data12 = pd.read_excel('C:UsersVideos{}.xlsx'.format(i))
gxt = data12.iloc [:,0]
gyan = data12.iloc [:,1]
int= gyan.iloc[8:19]
comp= gyan.iloc[19:25]
seg= gyan.iloc[25:31]
A= max(int)   
B= max(comp)  
C= min(comp)
D= max(seg) 
s = pd.Series([A, B, C, D])

frame_data= [gyan, comp, seg]
result = pd.DataFrame(pd.concat(frame_data))
ws = wb.active
result_list = result.to_numpy()
print('Total rows = ', len(result_list))
for row in result_list.tolist():
ws.append(row)
wb.save(output)

这将有助于运行所有350个文件并将其保存到输出文件中。还要相应地更改frame_data。我希望这对你有用。

流动代码为您提供文件夹中的所有文件

filenames = listdir(r'C:UsersVideos')
count = 1
for file in filenames:
print (file)
....... 
#At the end
output = "output-" + str(count) + ".xlsx"
count = count + 1
result = pd.concat(frame_data)
result.to_excel(output, sheet_name='modify_data', index=False) 

对于主文件,可以将数据保存在pandas数据帧中,并在循环中不断追加每个文件。

最新更新