[TIP] Python 외부 출력 간 CSV 공백 생성 문제 해결

2022. 8. 25. 18:26
728x90

개발 및 연구의 결과물이나, 학습 데이터를 위해 대규모 데이터를 CSV로 출력해야 할 때가 존재한다.

 

Pandas를 활용하여, 처리하는 것이 일반적이긴 하나, CSV 함수만을 이용하여 외부로 출력했을 때, 공백 줄이 생기는 문제가 발생한다.

 

오늘은 이러한 문제를 해결하는 방법을 알아보자.

 

아래의 예시는 실제 RTLS 프로젝트에 사용된 함수를 나타내며, 실제 해당 함수를 통해 수집 데이터를 출력하는 경우, 공백과 함께 CSV 파일이 생성되는 것을 확인할 수 있다.

import csv
from datetime import datetime

# Define the exporting csv function.
def export(token, mac_info, rssi_info, txpower_info):

	# Define file path (write your specific path).
	path = 'C:\\Users\\~~~~'
    
    # Define timestap.
    time_stamp =  str(datetime.now().strftime('%Y%m%d%H'))
    
    # Define file type <.csv>.
    file_type = '.csv'
    
    # Getting the beacon datas (list to dictionary).
    gen_dict = dict(MAC = mac_info, RSSI = rssi_info, POWER = txpower_info)
    
    try:
    	# Generate timestamp_gateway.csv.
    	with open(path + time_stamp + file_type, 'w') as outfile:
        	# Creating a csv writer object.
        	writerfile = csv.writer(outfile)
            
        	# Writing dictionary keys as headings of csv.
        	writerfile.writerow(gen_dict.keys())
            
            # Writing list of dictionary.
            writerfile.writerows(zip(*gen_dict.values()))
            
    except IOError:
    	pass
        
    return

 

다음과 같이 <newline = "">을 추가하여, 공백 생성 없이 수집된 데이터만을 CSV 파일로 생성할 수 있다.

# EX) with open(filename, "w", newline="") as result_file :

with open(FILE_PATH + TIME_STAMP + GW_NUMBER + FILE_TYPE, 'w', newline="") as outfile:

 

728x90

BELATED ARTICLES

more