1. 파일 열기와 닫기
file = open('data.txt')
content = file.read()
file.close()
2. 파일 열기와 닫기를 '한번에'
with open('data.txt') as file:
content = file.read()
3. 줄 단위로 읽기
content = []
with open('data.txt') as file:
for line in file:
content.append(line)
1. 쓰기 모드로 파일을 열기
with open('data.txt', 'w') as file:
file.write('hello')
👉 아래와 같이 사용할 수 있다.
# matplotlib의 일부인 pyplot 라이브러리를 불러옵니다.
import matplotlib.pyplot as plt
# 월별 평균 기온을 선언
years = [2013, 2014, 2015, 2016, 2017]
temperatures = [5, 10, 15, 20, 17]
# 막대 그래프의 막대 위치를 결정하는 pos를 선언합니다.
pos = range(len(years)) # [0, 1, 2, 3, 4]
# 높이가 온도인 막대 그래프를 그립니다.
# 각 막대를 가운데 정렬합니다.
# bar(x축, y축, 위치)
plt.bar(pos, temperatures, align='center')
# 각 막대에 해당되는 연도를 표기합니다.
# xticks(어디에, 무엇을)
plt.xticks(pos, years)
plt.show()
import matplotlib.font_manager as fm
font = fm.FontProperties(fname='./NanumBarunGothic.ttf')
plt.title('1월 중 기온 변화', fontproperties=font)
plt.xticks(pos, dates, rotation='vertical', fontproperties=font)
plt.ylabel('온도', fontproperties=font)
plt.tight_layout()
- Comma Separated Value의 줄임말
👉 comma 외에 '|'를 사용하여 구분할 수도 있다.- 각 열이 특정한 의미를 가짐
- 용량이 excel 파일에 비해 작다.
- 데이터 오염에 취약하다.(열이 분리될 가능성이 있다.)
⚡ 데이터에 "," 가 포함된 경우 큰따옴표를 이용해 데이터를 감싼다.
import csv
with open('movies.csv') as file:
# delimiter: 어떤 기호로 데이터들이 분리되어 있는지 명시
reader = csv.reader(file, delimiter=',')
for row in reader:
print(row) # row는 리스트로 이루어져 있다.
# src는 csv 파일, dst는 json 파일
books = []
with open(src_file) as src:
reader = csv.reader(src, delimiter=',')
for row in reader:
# 책 정보를 저장하는 딕셔너리를 생성합니다.
book = {
"title": row[0],
"author": row[1],
"genre": row[2],
"pages": int(row[3]),
"publisher": row[4]
}
books.append(book)
# dst 파일에 json_string을 추가한다.
with open(dst_file, 'w') as dst:
json_string = json.dumps(books)
dst.write(json_string)
numbers = [1, 2, 3, 4]
new_numbers = [n+1 for n in numbers]
numbers[1, 2, 3, 4, 5, 6]
even = [n for n in numbers if n % 2 == 0]
numbers = [-1, 3, 2, -5, 5, 100]
sort_by_abs = sorted(numbers, key=abs) # 절댓값 기준 정렬
numbers = ['cherry', 'apple', 'banana']
sort_by_abs = sorted(numbers, key=reverse) # 역순 정렬
# ['banana', 'apple', 'cherry']
👉 이 경우 각 원소를 reverse했을 때를 기준으로 정렬하게 된다. 즉, 각각 'yrr~', 'elp~', 'ana~' 가 되므로 알파벳 순서가 가장 낮은 것부터 banana -> apple -> cherry 순이 되는 것이다.
[데이터 정렬하기 예시]
⚡ 주의할 점
pairs = [
('time', 8),
('the', 15),
('turbo', 1),
]
# pair는 튜플
def get_freq(pair):
return pair[1]
# pairs는 튜플로 이루어진 리스트
def sort_by_frequency(pairs):
return sorted(pairs, key=get_freq)
print(sort_by_frequency(pairs))
# [('turbo', 1), ('time', 8), ('the', 15)]
1. 공통점
2. 차이점
hello = ('a', 'b', 'c')
hello[0] = 'hi' # 에러
hello.append('d') # 함수 없음
🐧 이 글은 엘리스 AI 트랙 과정 중 '실전 데이터 분석' 강의 내용을 바탕으로 작성 되었습니다.