본문 바로가기
프로그래밍/Python

[python] txt, csv 파일 쓰기/읽기

by JR2 2022. 4. 28.

Version : 3.10.4

 

파일을 열었으면 꼭 닫아줘야한다고 한다.

 

w : write

r : read

a : append

 

myFile = open('a.txt', 'w')
myFile.write("hello")
myFile.close()

a.txt라는 파일을 열어서 hello를 적는다.

만약 a.txt가 있다면 덮어쓴다.

만약 a.txt가 없다면 생성한다.

 

myFile = open('a.txt', 'r')
print(myFile.read())
myFile.close()

a.txt라는 파일을 읽어서 출력하는 코드이다.

 

myFile = open('a.txt', 'a')
myFile.write(" world!")
myFile.close()

a.txt라는 파일에 " world!"를 추가로 입력하는 코드이다.

 

현재 a.txt에는 hello가 작성되어 있었으니,

위의 코드를 실행하고 a.txt를 확인해보면 hello world!가 적혀있을 것이다.

 

 


 

csv 파일도 거의 완전 동일하게 쓸 수 있다.

csv 파일은 엑셀 혹은 numbers로 열 수 있는 확장자이다.

 

myFile = open('a.csv', 'w')
myFile.write('김xx,24세,지렁이')
myFile.write('\n이xx,25세,고양이')
myFile.close()

a.csv라는 파일을 열어서 콤마(,)로 구분된 것들을 write한다.

만약 a.csv가 있다면 덮어쓴다.

만약 a.csv가 없다면 생성한다.

 

 

 

myFile = open('a.csv', 'a')
myFile.write('\n이빵돌,3세,강아지')
myFile.close()

a.csv라는 파일을 열어서 위의 내용을 추가한다.

 

myFile = open('a.csv', 'r')
print(myFile.read())
myFile.close()

이런 결과를 볼 수 있을 것이다

 

read() 결과

 

a.csv 파일 모습

 

댓글