[TIL] Day.16 Python 입출력(file)

eslim·2020년 8월 9일
0

Python

목록 보기
7/12
post-thumbnail

1. 파일 생성(w)

파일객체 = open(파일 이름, 파일 열기 모드)
f.close()
  • 파일 열기 모드
    r : 읽기
    w : 쓰기
    a : 추가
f = open("new_file.txt", 'w')
f.close()

2. 프로그램의 외부에 저장된 파일 읽는 방법(r)

2-1 readline() 함수

f = open("C:/새파일.txt", 'r')
line = f.readline()
print(line)
f.close()
  • 파일을 읽기 모드르 열고, 파일의 첫번째 줄을 출력하는 경우

2-2 readlines() 함수

f = open("C:/새파일.txt", 'r')
lines = f.readlines()
for line in lines:
    print(line)
f.close()
  • readlines 함수는 파일의 모든 줄을 읽어서 리스트로 출력한다.

2-3 read() 함수

f = open("C:/새파일.txt", 'r')
data = f.read()
print(data)
f.close()

3. 내용 추가(a)

f = open("C:/새파일.txt",'a')
for i in range(11, 20):
    data = "%d번째 줄입니다.\n" % i
    f.write(data)
f.close()

0개의 댓글