파일 불러오기
확장자에 따른 파일 불러오기
CSV 파일 (.csv)
import pandas as pd
df = pd.read_csv('file.csv')
Excel 파일 (.xls, .xlsx)
import pandas as pd
df = pd.read_excel('file.xlsx')
JSON 파일 (.json)
import pandas as pd
df = pd.read_json('file.json')
텍스트 파일 (.txt, .dat 등)
import pandas as pd
df = pd.read_csv('file.txt', delimiter = '\t')) # 탭으로 구분 된 경우
파일 저장하기
확장자에 따른 파일 저장하기
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 파일 (.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)
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("텍스트 파일이 생성되었습니다.")