CSV 파일 (.csv)
pandas 라이브러리의 read_csv() 함수 사용# 예시 코드
import pandas as pd
df = pd.read_csv('file.csv')
Excel 파일 (.xls, .xlsx)
pandas**의 read_excel() 함수를 사용# 예시 코드
import pandas as pd
df = pd.read_excel('file.xlsx')
JSON 파일 (.json)
pandas**의 read_json() 함수를 사용import pandas as pd
df = pd.read_json('file.json')
텍스트 파일 (.txt, .dat, 등)
pandas**의 read_csv() 함수를 사용import pandas as pd
df = pd.read_csv('file.txt', delimiter='\\t') # 만약 탭으로 구분되어 있다면 delimiter='\\t'를 사용
참고_구글 코랩에서 데이터 파일 읽어 들이는 법
<aside>
✅ 먼저 드라이브 마운트를 해준 후 구글 드라이브에 파일 업로드
</aside>
드라이브 마운트 코드를 사용하여 내 드라이브로 접근
from google.colab import drive
drive.mount('/content/drive')
# 파일 경로
root = "/content/drive/MyDrive/스파르타코딩클럽_데이터분석을위한파이썬"
# 파일 이름 붙여서 파일 경로 완성
file_address = root + "/ssec2403(통계표).xlsx"
# 위에서 지정한 파일 경로 활용하여 불러오기
import pandas as pd
df = pd.read_excel(file_address)
CSV 파일 (.csv)
import pandas as pd
data = {
'Name': ['John', 'Emily', 'Michael'],
'Age': [30, 25, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)
excel_file_path = '/content/sample_data/data.csv'
df.to_csv(excel_file_path, index = False)
print("csv 파일이 생성되었습니다.")
Excel 파일 (.xls, .xlsx)
import pandas as pd
data = {
'Name': ['John', 'Emily', 'Michael'],
'Age': [30, 25, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
df = pd.DataFrame(data)
excel_file_path = '/content/sample_data/data.xlsx'
df.to_excel(excel_file_path, index = False)
print("Excel 파일이 생성되었습니다.")
JSON 파일 (.json)
import json
data = {
'Name': ['John', 'Emily', 'Michael'],
'Age': [30, 25, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
json_file_path = '/content/sample_data/data.json'
# json 파일을 쓰기모드로 열어서 data를 거기에 덮어씌우게 됩니다.
with open(json_file_path, 'w') as jsonfile:
json.dump(data, jsonfile, indent=4)
print("JSON 파일이 생성되었습니다.")
텍스트 파일 (.txt, .dat, 등)
data = {
'Name': ['John', 'Emily', 'Michael'],
'Age': [30, 25, 35],
'City': ['New York', 'Los Angeles', 'Chicago']
}
text_file_path = '/content/sample_data/data.txt'
with open(text_file_path, 'w') as textfile:
for key, item in data.items():
textfile.write(str(key) + " : " + str(item) + '\\n')
print("텍스트 파일이 생성되었습니다.")