
f = open('file_name', 'mode')
f= = open('file_name', 'w')
f.write(str)
f.close()
f = open('newFile.txt','a') # 파일을 추가 모드로 열기
for i in range(6,11): # for문: i가 6~10까지 반복
data = "%d번째 줄입니다.\n"%i
f.write(data)
f.close()
for문을 이용해 반복하여 문자열 쓰기try:
f = open('myFile.txt', 'r') # 'myFile.txt' 파일 읽기 모드로 열기
file_text = f.read() # 파일 내용 읽은 후에 변수에 저장
f.close() # 파일 닫기
except FileNotFoundError as e:
print(e)
else:
print(file_text) # 변수에 저장된 내용 출력
readline() : 파일에서 한줄을 읽고 반환readlines() : 모든 줄을 읽어들인 후 리스트로 반환# while문을 이용하여 파일 한줄씩 읽기
f = open("newFile.txt", 'r') # 파일을 읽기 모드로 열기
line = f.readline() # 문자열 한 줄 읽기
while line: # line이 공백인지 검사해서 반복 여부 결정
print(line, end="") # 문자열 한 줄 출력(줄 바꿈 안 함)
line = f.readline() # 문자열 그 다음 한 줄 읽기
f.close() # 파일 닫기
close()로 파일 닫기가 필요with open('file_name', 'mode') as f:
[명령문]
with open('file_name', 'w') as f:
f.write(str)
with open('file_name', 'r') as f:
data = f.read()
9 x 1 = 9
9 x 2 = 18
...
9 x 9 = 81
with open("gugudan9.txt", 'r') as f:
for line in f.readlines():
print(line, end="")
requests 라이브러리 사용import requests
# requests로 획득한 데이터를 txt파일로 저장
url = "https://docs.python.org/3.12/whatsnew/3.12.html#math"
response = requests.get(url)
if response.status_code == 200: #상태코드 확인 200이 성공
with open('python_doc.txt', 'w') as f:
f.write(response.text)
wget 사용# !wget을 이용하여 파일 저장
!wget https://docs.python.org/3.12/whatsnew/3.12.html#math -O python_math.txt
gdown 라이브러리 사용import gdown
gdown.download("<파일 다운로드 URL>", "<파일명>")
# 인코딩 형식 확인하기
import chardet
chardet.detect(data)
# 인코딩 형식지정하여 파일 읽기
with open(<파일명>, encoding=<인코딩형식>) as f:
data = f.read()
# 폴더위치 지정
folder = "폴더명"
# 파일명 지정
file = "파일명"
# 경로결합
file_path = os.path.join(folder, file)
folder = "/content/drive/MyDrive/LikeLion/!수업자료"
for file in os.listdir(folder):
file_path = os.path.join(folder, file)
print(f"{file} :{file_path}")
# "\n"문자열 제거, 각 행의 콤마(,)를 기준으로 문자열 분할
with open('sample_data.csv', 'r') as c:
for line in c:
line = line.rstrip("\n")
print(line.split(','))
import csv
# `csv.reader`메서드를 활용한 읽기
with open('sample_data.csv', 'r') as c:
csvrows = csv.reader(c)
header = next(csvrows) # 첫번째줄을 읽어서 header에 저장
print("header", header)
for row in csvrows:
print(row)
# `csv.DictReader`메서드를 활용한 읽기
with open('sample_data.csv', 'r') as c:
rows = csv.DictReader(c)
for row in rows:
print(row)
# `csv.writer`메서드를 활용한 쓰기
with open('output.csv', 'w') as c:
rows = csv.writer(c)
# 헤더 작성
rows.writerow(['Name', 'Age', 'City'])
# 데이터 작성
rows.writerow(['Alice', 30, 'New York'])
rows.writerow(['Bob', 25, 'Los Angeles'])
# `csv.DictWriter`메서드를 활용한 쓰기
with open('outputDict.csv', 'w') as c:
fieldnames = ['Name', 'Age', 'City']
rows = csv.DictWriter(c, fieldnames=fieldnames)
# 헤더 작성
rows.writeheader()
# 데이터 작성
rows.writerow({'Name': 'Alice', 'Age': 30, 'City': 'New York'})
rows.writerow({'Name': 'Bob', 'City': 'Los Angeles'})
# 2차원 배열 생성
np.array([[1,2,3],
[4,5,6],
[7,8,9]])
numpy.arange(start, stop, step)np.arange(0.1, 1.1, 0.1)
numpy.linspace(start, stop, num, endpoint=True)np.linspace(1, 10, 3)
ones(shape) : 1로 채워진 배열zeros(shape) : 0으로 채워진 배열full(shape,value) : value로 채워진 배열eye(N),indentity(N) : N차원 단위행렬ndim : ndarray의 차원shape : 각 차원의 ndarray 크기를 튜플 형태로 나타냄size : ndarray에 있는 요소의 총 수dtype : ndarray의 데이터 유형T : 전치행렬, ndarray의 전치된 결과 반환(행열 바꾸기)reshape(shape) 함수를 이용array.reshape(shape)
numpy.reshape(array, shape)
astype함수 또는 특정 데이터 유형의 이름을 가진 함수 사용array.astype(nupmy.datatype)
numpy.datatype(array)
array.astype('datatype')
[행 인덱스, 열 인덱스]
array[-1,-1]
array[boolean array]
array[<조건문>]
array[array % 2 ==0]
array[array > 5]
row = [0,1]
col = [2,1]
a1 =array[row,col]
array[0,2] =10
array,a1
numpy.random.rand(shape)
numpy.random.randint(low, high, size=shape)
numpy.random.normal(loc=평균, scale=표준편차, size=shape)
save savez 함수 이용load 함수 이용numpy.save(<파일명>, array)
numpy.savez(<파일명>, **arrays)
numpy.load(<파일명>)
five =np.array([[28, 2, 11],
[27, 27, 21],
[11, 5, 24]])
five[[0,1,2],[0,1,2]]
seven= np.array([[ 7, 47, 84, 6, 46],
[17, 28, 4, 62, 27],
[77, 85, 64, 73, 4]])
seven.sum()
s1 = [ 7, 47, 84, 6, 46]
sum(s1)/len(s1)
seven.mean(axis=1)
seven.std(axis=0)
seven.cumsum(axis=1)
seven.cumprod(axis=0)