산업공학과를위한 프로그래밍입문 (w/ 파이썬 ) PART II : Python 활용 가천대학교 산업경영공학과 최성철교수
간단한파일다루기
[ 생각해보기 ] 우리는어떻게프로그램을시작하나? 보통은이렇게생긴아이콘을누른다! 그러나실제로는아이콘이아닌 실행파일 을실행시키는것아이콘을클릭하고오른쪽마우스클릭 속성 을선택해볼것
[ 생각해보기 ] 옆과같은화면이나올것이다대상에있는 text전체를복사한후 Windows key + r을누르고 cmd 를입력후엔터를칠것
[ 생각해보기 ] 옆과같이콘솔창이나오면오른쪽마우스를클릭 붙여넣기 메뉴선택한후텍스트를입력하면해당프로그램이실행됨 아이콘을누르는것은실제로는 파일의실행을명령하는것
파일의구성 파일은파일을담고있는디렉토리와파일로나눌수있음 디렉토리 (Directory) - 폴더또는디렉토리로불림 - 파일과다른디렉토리를포함할수있음 파일 (File) - 컴퓨터에서정보를저장하는논리적인단위 (wikipedia) - 파일은파일명과확장자로식별됨 ( 예 : hello.py) - 실행, 쓰기, 읽기등을할수있음
[ 참조 ] 파일의구조 ( 윈도우 ) 디렉토리 파일
[ 참조 ] 파일의구조 ( 리눅스 ) Ages 서버에서 ll R 을입력하면현재디렉토리를기준으로하위디렉토리및파일확인가능 디렉토리 파일
파일의종류 모든프로그램은파일로구성되어있음 파일은크게 Text 파일과 Binary 파일로나뉨 Binary 파일 - 컴퓨터만이해할수있는형태인이진 ( 법 ) 형식으로저장된파일 - 일반적으로메모장으로열면내용이깨져보임 ( 메모장해설불가 ) - 엑셀파일, 워드파일등등 Text 파일 - 인간도이해할수있는형태인문자열형식으로저장된파일 - 메모장으로열면내용확인가능 - 메모장에저장된파일, HTML 파일, 파이썬코드파일등 - 컴퓨터는 Text 파일을처리하기위해 Binary 파일로변환시킴 ( 예 : pyc 파일 ) - 모든 Text 파일도실제는 Binary 파일, ASCII/Unicode 문자열집합으로저장되어사람이읽을수있음
[ 참고 ] ASCII 코드표
파일읽기 my_file = open("i_have_a_dream.txt", "r") # 파일열기 contents = my_file.read() # 파일전체읽기 print type(contents), contents # 전체값출력, 출력형태는 string Txt 파일 my_file.seek(0) # 파일처음으로돌아가기 content_list = my_file.readlines() # 파일전체를 list 로반환 print type(content_list), content_list # 리스트값출력 i = 0 my_file.seek(0) # 파일처음으로돌아가기 while 1: line = my_file.readline() if not line: break print str(i) + " === " + line, # 한줄씩값출력 i = i + 1
파일읽기 2 Txt 파일 my_file = open("i_have_a_dream.txt", "r") contents = my_file.read() word_list = contents.split(" ") line_list = contents.split("\n") # 빈칸기준으로단어를분리리스트 # 한줄씩분리하여리스트 print "Total Number of Characters :", len(contents) print "Total Number of Words:", len(word_list) print "Total Number of Lines :", len(line_list)
디렉토리정보받아오기 강의코드다운로드를아래정보입력 git clone https://github.com/teamlab/gachon_python_class.git import os print os.listdir("./gachon_python_class") # 해당폴더의파일리스트를리스트로반환 #os.walk(top,topdown=true, oneerror=none,followlinks=false) #Return Info: dirpath, dirnames, filenames # os.walk 하위디렉토리정보를재귀적으로반환 # 반환형식은현재디렉토리, 디렉토리리스트, 파일리스트 for curdir, dirs, files in os.walk('./gachon_python_class'): #.gachon_python_class 디렉토리에서파일정보를반환 print "Current Directory :", curdir print "Directory List :", dirs print "File List :", files print # 현재디렉토리 # 디렉토리리스트 # 파일리스트 root_dir = "./gachon_python_class/lecture/w8_module/midterm_package" file_list = os.listdir(root_dir) for file in file_list: print "File Name -", file, # 디렉토리파일들을반환 # 특정디렉토리에서파일리스트반환 if os.path.isfile(root_dir+"/"+file): print "is File if os.path.isdir(root_dir+"/"+file): print "is Directory # 파일여부확인 os.path.isfile # 디렉토리여부확인 os.path.isdir
파일쓰기 import os with open("file_name_list.txt","w") as f: # 파일열기 with 구문을사용하면 with 구문이끝날때까지 f 라는이름으로파일객체사용가능 # 파일을처리할때 r 은파일읽기, w 는파일쓰기, a 는파일추가로쓰기임 ( 참고 ) for curdir, dirs, files in os.walk('./gachon_python_class'): # 재귀적파일정보반환 f.write("current Directory :" + curdir + "\n") # 현재디렉토리정보를파일에쓰기 if len(dirs): # 현재디렉토리에하위디렉토리가있을경우 f.write("directory List" + "\n") dirlist = "" for dir in dirs: dirlist = dirlist + dir + "\t" + str(len(files)) + "\n # 각디렉토리이름과가지고있는파일개수를문자열로만들기 f.write(dirlist+"\n") # 현재디렉토리내에있는하위디렉토리를정보를파일에쓰기 if len(files): # 현재디렉토리에하위파일이있을경우 f.write("file List List" + "\n") filelist = "" for file in files: filelist = filelist + file + "\t" + str(os.path.getsize (curdir+"/"+file))+"kb" + "\n # 각파일의이름과크기를문자열로만들기 f.write(filelist+"\n") # 현재디렉토리내에있는파일의정보를파일에쓰기 f.write(("-"*60)+"\n")
Q&A