f = open(파일이름, 파일 열기 모드,encoding='인코딩방식')
f.close()
파일모드
r : 읽기
w : 쓰기 - 새로운 내용을 덮어쓰기
a : 쓰기 - 기존 파일의 내용에 추가방식
t : text. 기본값
b : 이진모드. binary모드. 이미지,동영상
파일 생성하기
경로 생략시 현재 디렉토리에 생성된다. 생성하려는 파일이 없는 상태에서 w(쓰기)모드로 열면 새로운 파일이 생성된다. 만약 이미 존재할 경우에는 기존 파일의 내용이 사라지고 덮어쓰기 된다.
f = open("경로/새파일.txt",'w')
f.close()
파일 쓰기
파일을 w(쓰기)모드로 열고, 출력할 내용을 작성 후 write함수를 사용해서 출력해준다.
f = open("경로/새파일.txt",'w')
for i in range(1,11)
data = "%d번째 줄입니다.\n" %i
f.write(data)
f.close()
파일 읽기
파일을 r(읽기)모드로 열고, 함수를 활용해서 읽어준다.
readline() : 한줄씩 읽기
f=open("새파일.txt",'r')
while True :
line = f.readline() #한줄읽기
if not line: break #파일의 끝
print(line,end="")
f.close()
readlines() : 한줄씩 리스트형태로 반환
f=open("새파일.txt",'r')
lines=f.readlines() #한줄씩 리스트형태로 담기
for line in lines:
print(line,end="")
f.close()
read() : 한번에 읽기
f=open("새파일.txt",'r')
print(f.read()) #한번에 읽기
f.close()
파일 다른 이름으로 저장하기
원본파일을 r(읽기)모드로 열어서 w(쓰기)모드로 열은 파일에 써준다.
inf = open("C:/webtest/resource/apple.gif","rb") #b는 binary모드
outf = open("apple2.gif","wb")
while True:
indata = inf.read() #복사 할 원본 파일 데이터 읽기
if not indata: break
outf.write(indata) #저장 할 파일에 출력하기
inf.close()
outf.close()
기존파일에 새로운 내용 추가하기
파일을 a(추가해서 쓰기)모드로 열고, 출력할 내용을 작성후 write함수로 출력해준다.
f=open("새파일.txt",'a')
for i in range(11,20):
data = "%d번째 줄입니다.\n" %i
f.write(data)
f.close()
with문과 함께 사용하기
with문을 사용하면 자동으로 close() 역할을 처리해준다.
with open("foo.txt","w") as f:
f.write("Life is too short, you need python")
sys 모듈로 매개변수 주기
1. sys1.py 파일 만들어주기
f = open("sys1.py",'w',encoding='UTF-8')
data="""
#sys1.py
import sys
args=sys.argv[1:]
for i in args:
print(i)
"""
f.write(data)
f.close()
2. prompt창에서 sys1.py 실행시 매개변수 주기
(base) PS C:\Users\SMKIM> cd C:\webtest\6.python\doit
(base) PS C:\webtest\6.python\doit> python sys1.py aaa bbb ccc
aaa
bbb
ccc
(base) PS C:\webtest\6.python\doit>
결과 : 매개변수 값을 넣어서 실행해준다.
1. sys2.py 파일 만들어주기
f = open("sys2.py",'w',encoding='UTF-8')
data="""
#sys2.py
import sys
args=sys.argv[1:]
for i in args:
print(i.upper(),end=' ')
"""
f.write(data)
f.close()
2. prompt창에서 sys2.py 실행시 매개변수 주기
(base) PS C:\webtest\6.python\doit> python sys2.py python is very fun
PYTHON IS VERY FUN
(base) PS C:\webtest\6.python\doit>
결과 : 매개변수 값을 넣어서 실행해준다.
os.path모듈로 파일정보 조회하기
파일, 폴더 구분하기 : isfile() / isdir()
import os.path
file="새파일.txt" #상대경로
if os.path.isfile(file):
print(file,"은 파일입니다.")
elif os.path.isdir(file) :
print(file,"은 폴더입니다.")
# 새파일.txt 은 파일입니다.
file="C:\\webtest\\6.python\\doit" #절대경로
if os.path.isfile(file):
print(file,"은 파일입니다.")
elif os.path.isdir(file) :
print(file,"은 폴더입니다.")
# C:\webtest\6.python\doit 은 폴더입니다.
파일 존재여부 파악하기 : exists(file)
import os.path
file="없는파일.txt" #상대경로
if os.path.exists(file) :
print(file,"은 존재합니다.")
else :
print(file,"은 없습니다.")
# 없는파일.txt 은 없습니다.
import os.path
file="새파일.txt" #상대경로
if os.path.exists(file) :
print(file,"은 존재합니다.")
else :
print(file,"은 없습니다.")
# 새파일.txt 은 존재합니다.
파일 사이즈 파악하기 : getsize()
import os.path
print(os.path.getsize("새파일.txt"))
# 333
os모듈로 경로, 파일, 폴더 등 활용하기
os.getcwd() : 현재 작업 폴더 위치
os.listdir() : 작업 폴더의 하위 파일 목록 출력하기
os.chdir("변경 할 경로") : 작업 폴더 변경
os.mkdir("생성 할 폴더명") : 폴더 생성
os.rmdir("제거 할 폴더명") : 폴더 제거
엑셀파일 읽기
엑셀파일 읽기에는 외부모듈이 필요하다.
xlsx(Excel2007이후 확장명) : openpyxl 모듈 (3.9버전에서는 따로 설치 필요 없음)
xls(Excel2003이전 확장명) : xlrd모듈
xlsx파일 읽기
import openpyxl
load_workbook("엑셀파일명") : 엑셀파일 로드
worksheets[sheet번호] : 읽을 sheet 데이터 번호(0부터 시작)
rows : 행들
enumerate(리스트) : 리스트에서 인덱스와 데이터값을 리턴
import openpyxl
data=[]
for row in openpyxl.load_workbook("C:\\webtest\\resource\\excel\\sales_2015.xlsx").worksheets[0].rows:
line=[]
for l, d in enumerate(row):
line.append(d.value)
data.append(line)
print(data)
xls 파일 읽기
from xlrd import open_workbook
open_workbook("엑셀파일명") : 엑셀파일 전체
nsheets : 엑셀의 sheet 갯수
sheets() : 엑셀의 sheet데이터들
sheet.name : sheet의 이름
sheet.nrows : sheet에서 행의 수
sheet.ncols : sheet에서 컬럼의 수
from xlrd import open_workbook
print(open_workbook("C:\\webtest\\resource\\excel\\ssec1804.xls").nsheets)
# 26
for worksheet in open_workbook("ssec1804.xls").sheets():
print("worksheet 이름:",worksheet.name)
print("행의 수:",worksheet.nrows)
print("컬럼의 수:",worksheet.ncols)
for row_index in range(worksheet.nrows):
for column_index in range(worksheet.ncols):
print(worksheet.cell_value(row_index,column_index),",",end="")
print()
'프로그래밍언어 > Python' 카테고리의 다른 글
[Python] 모듈 (0) | 2021.12.29 |
---|---|
[Python] 클래스 (0) | 2021.12.29 |
[Python] 함수 (0) | 2021.12.28 |
[Python] 컴프리헨션(Comprehension) (0) | 2021.12.27 |
[Python] 파이썬 자료형 : 불 (0) | 2021.12.27 |