Python 13

Joy_all·2021년 3월 31일
0

Python

목록 보기
9/9

📒 파일입출력

open("파일명","모드") 내장함수

w-파일쓰기, r-파일읽기, a-파일에 추가

test.txt -> testFile
test1234

📍 파일읽기

f = open("test.txt","r")
print(f)

<_io.TextIOWrapper name='test.txt' mode='r' encoding='cp949'>

📍 해당파일의 내용 첫줄만 읽어오기

f = open("test.txt","r")
print( f.readline() )

test.txt -> testFile

📍 파일 불러오기 (다쓴후 파일 자원해제 해야함)

while True:
    line = f.readline()

    if not line:
        break

    print(line)

f.close()   # 자원해제

test.txt -> testFile
test1234

📍 파일의 내용을 리스트로 읽어오기

f2 = open("test.txt","r")
print(f2.readlines())

test1234
['test.txt -> testFile\n', 'test1234']

f2 = open("test.txt","r")
for i in f2.readlines():
    print(i)
f2.close()

test.txt -> testFile
test1234

📍 .csv 파일 읽어오기

f3 = open("birth.csv","r")
for a in f3.readlines():
    print(a)

f3.close()

"시점",전국,서울특별시,부산광역시,대구광역시,인천광역시,광주광역시,대전광역시,울산광역시,세종특별자치시,경기도,강원도,충청북도,충청남도,전라북도,전라남도,경상북도,경상남도,제주특별자치도
"2015",438420,83005,26645,19438,25491,12441,13774,11732,2708,113495,10929,13563,18604,14087,15061,22310,29537,5600
"2016",406243,75536,24906,18298,23609,11580,12436,10910,3297,105643,10058,12742,17302,12698,13980,20616,27138,5494
"2017",357771,65389,21480,15946,20445,10120,10851,9381,3504,94088,8958,11394,15670,11348,12354,17957,23849,5037

📍 이미지 파일은 안됨.

f4 = open("2.jpg","r")
for a in f4.readlines():
    print(a)

f4.close()

FileNotFoundError: [Errno 2] No such file or directory: '2.jpg'

📒 파일 쓰기

기본적으로 덮어쓰기 (주의)

📍 파이참에 파일 생성

f5 = open("fileTest.txt","w")

data = "itwill busan"

for i in range(0,len(data)):
    # print(data[i])
    f5.write(data[i])
f5.close()

fileTest.txt
-> itwill busan

📍 특정위치에 파일 생성

f6 = open("D:/JSP/fileTest1.txt","w")
for i in range(1,6):
    f6.write(" %d 입력 \n" %i)

D:\JSP\fileTest1.txt 내 컴퓨터에 파일 생성
1 입력
2 입력
3 입력
4 입력
5 입력

📍 파일에 내용추가

f7 = open("test.txt","a")

f7.write("hello append~!!")
f7.close()

test.txt -> 6hello append~!! 추가됨

📍 파일 내용 뒤집기!

  • 파일을 리스트로 읽을 수 있음.
  • fileTest.txt 파일의 내용을 역순으로 뒤집어서 사용
fo = open("fileTest.txt","r")

lists = fo.readlines()

fo.close()

print(lists)
lists.reverse()
print(lists)

fo2 = open("fileTest.txt","w")

for i in lists:
    fo2.write(i)

fo2.close()

profile
beginner

0개의 댓글