프로그래밍 문법/python 64

파이썬으로 파일 읽기, 쓰기

파일 읽기 1. 기본 내장 함수 words = [] f = open("words.txt", 'r') while True: line = f.readline().strip("\n") if not line: break words.append(line) ''' 코드처리 ''' f.close() 2. 기본 내장 함수 (with이용) with open('경로/파일이름', 'r') as f: line = f.read() print(line) 3. 판다스(pandas) read_csv csv파일을 읽을 때 사용 import pandas as pd pd.read_csv("경로/파일이름") 파일 쓰기 1. 기본 내장 함수 f = open("경로/파일이름", 'w') for i in range(10): line = f"{i..

폴더내의 하위 파일 모두 불러오기 및 접근

하위파일 모두 불러오기 import os import pandas as pd folder="name_of_folder" #디렉토리 내에 폴더 subdir_names=os.listdir(folder) #subdir_names에 폴더내의 모든 파일이름이 들어간다 for file_name in subdir_names: csv=pd.read_csv(folder+"\\"+file_name) #하위 디렉토리 접근시 역슬러시(원화표시) 하위 파일(or 폴더)에 접근하기 # 폴더 data_path = '/gdrive/My Drive/folder' # 파일 file=os.path.join(data_path,"file") print(file) /gdrive/My Drive/folder/file

파일 불러오기 , 쓰기

1. 파일 읽어오기 (1) 내장 모듈 fileMatrix = [] with open("21.csv",'r') as file: for lineContent in file: fileMatrix.append(lineContent.strip('\n').split(",")) for lineContent in file: - file에 있는 한줄씩 lineContent에 저장 (문자열형식) ​ lineContent.strip('\n').split(",") - lineContent에 \n은 없앰 - split(",") : 리스트를 만들어서 ","를 기준으로 나누어서 한 index씩 넣음 fileMatrix = [] with open('data.csv','r',encoding='utf-8') as fileOpen: li..

파이썬 입력 속도 빠르게 하기

1. input() 보다 sys.stdin.readline()을 이용한다 sys.stdin.readline() 이 속도가 빠르다. 하지만 \n까지 같이 입력받는다. 따라서 sys.stdin.readline().rstrip() 를 써서 개행을 제거하고 입력받는다. ​ ex) import sys # 개행까지 함께 입력 a=sys.stdin.readline() print(a,"end") # 개행제외 함께 입력 b=sys.stdin.readline().rstrip() print(b,"end") 더보기 input input end input input end *c++은? https://blog.naver.com/ngoodsamari/221785816475 c++ 입출력 속도 빠르게하기 1. cin cout 입출력..

파이썬 진수변환 (10진수를 n진수로, n진수를 10진수로)

진수를 변환하는 방법은 다음과 같다 10진수를 n(2,8,16)진수로 바꾸는방법 10진수 x를 2진수로 바꾸려면 bin(x) , 10진수 x를 8진수로 바꾸려면 oct(x) 10진수 x를 16진수로 바꾸려면 hex(x) print(bin(11)) print(oct(11)) print(hex(11)) 타입은 모두 스트링 0b1011 (2진법은 앞에 0b가 붙는다) 0o13 (8진법은 앞에 0o가 붙는다) 0xb (16진법은 앞에 0x가 붙는다) * 2,8,16 진수가 아닌 다른 진수로 바꾸고 싶으면 다음 함수를 이용한다. def convert(n, base): ''' n: base진수로 바꿀 10진수 base : 진수 ''' q, r = divmod(n, base) if q == 0: return str(..

aliasing시 요소 수정과 재정의의 차이

리스트를 aliasing(b=t)했을 때 1. 리스트 자체를 재정의 하면 수정이 적용되지 않지만 2. 요소를 수정하면 수정이 적용된다 print("[리스트를 재정의]") b=[] t=[1,2,3] b=t print("전") print(b) t=[5,6,7] print("후") print(b) print() print("리스트 요소 수정") b=[] t=[1,2,3] b=t print("전") print(b) t[0]=5 t[1]=6 t[2]=7 print("후") print(b) 더보기 [리스트를 재정의] 전 [1, 2, 3] 후 [1, 2, 3] 리스트 요소 수정 전 [1, 2, 3] 후 [5, 6, 7]