2017-10-30 1 views
0

PLC의 변수 이름과 값을 포함하는 텍스트 파일을 만드는 FTP 서버가 있습니다.여러 텍스트 파일에서 데이터를 가져와 파이썬에서 Excel로 가져 오기

P_CASCADESTURING_MAIN.BR1.BRANDER_SP.fOpVal;System.Single;0 
P_Warmtepomo_MAIN_SP;0 

그래서 이분의 내가 4 개 텍스트 파일을 위하지만 서로 다른과를 ​​포함 할 것이다 : 그것은 새 파일을 (예를 들어 30 초마다)마다 선택 간격

텍스트 파일은 다음과 같이 것을 만들 값.

그래서 모든 파일 (예 : 4)을 읽고 시간에 각 변수의 값을 정렬하고이를 Excel 파일에 저장하는 코드를 파이썬으로 만들고 싶습니다. 그것은 다음과 같은 이름이 그래서

참고 FTP 서버가 작성하는 파일의 시간과 날짜를 포함

GetData_1.2017-10-30_161418 

어쩌면 내가 것 결국

그래서 시간에 변수를 주문하는 데 사용할 수 있습니다 (X 파일에서)이

P_CASCADESTURING_MAIN.BR1.BRANDER_SP.fOpVal;System.Single;0 (from file 1) 
P_CASCADESTURING_MAIN.BR1.BRANDER_SP.fOpVal;System.Single;2 (from file 2) 
P_CASCADESTURING_MAIN.BR1.BRANDER_SP.fOpVal;System.Single;3 (from file 3) 
P_CASCADESTURING_MAIN.BR1.BRANDER_SP.fOpVal;System.Single;4 (from file 4) 


P_Warmtepomo_MAIN_SP;0 (from file 1) 
P_Warmtepomo_MAIN_SP;1 (from file 2) 
P_Warmtepomo_MAIN_SP;2 (from file 3) 
P_Warmtepomo_MAIN_SP;3 (from file 4) 

같은 모양이 순서 랜덤되지 수 있는지 설명하는 그냥 것 엑셀 파일이 있습니다. 그것은 Excel 파일에있을 필요가 없습니다

답변

0

pandas 기반 솔루션 :

import os 
import pandas as pd 

# Path of directory containing the text files 
directory = '.' 

# Initialize empty dataframe collector 
dframe_collector = [] 

# For each file in the directory ... 
for file_name in os.listdir(directory): 
    if file_name.startswith('GetData'): 
     # Construct full path of file 
     file_path = os.path.join(directory, file_name) 

     # Read out file and store into a pandas dataframe 
     file_dframe = pd.read_csv(file_name, sep=';', header=None) 
     dframe_collector.append(file_dframe) 

# Concatenate individual dataframes into one single dataframe 
master_dframe = pd.concat(dframe_collector) 

# With newly created excel file ... 
with pd.ExcelWriter('summary.xlsx') as writer: 
    # For each unique parameter that occurs in the first column of the dataframe ... 
    for num, (name, group) in enumerate(master_dframe.groupby(0)): 
     # Write corresponding data rows to individual excel sheet 
     sheet_name = f'Sheet_{num}' 
     group.to_excel(writer, sheet_name=sheet_name, header=None, index=None) 
+0

감사합니다! 그는 엑셀 파일의 라인을 어떻게 주문합니까? 가장 오래된 파일은 맨 위에, 가장 새로운 파일은 끝에 넣고 싶습니다. 이 방법은 변수의 값을 시간 순서대로가집니다. – Cedric123

+0

나는 날짜순으로 디렉토리를 정렬하는 것이 좋습니다. 여기에 대한 게시물이 있습니다 : https://stackoverflow.com/questions/168409/how-do-you-get-a-directory-listing-sorted-by-creation-date-in-python – Samantha

+0

@ Cedric123'os.listdir (디렉토리)'는 알파벳 순서로 오름차순으로 디렉토리의 파일 이름을 산출하는 반복자입니다. 따라서 모든 파일 이름이 앞에서 언급 한'GetData_1.yyyy-MM-dd_HHmmss' 규칙을 따른다면 Excel의 데이터는 이미 오래된 것부터 가장 최신의 것으로 자동 정렬됩니다. – Xukrao

관련 문제