Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
Tags
- sql연습하기
- SQL
- 파이썬알고리즘
- 파이썬크롤링
- 판다스데이터분석
- SQL수업
- matplotlib
- 파이썬데이터분석
- 판다스그래프
- 주피터노트북판다스
- 맷플롯립
- 파이썬데이터분석주피터노트북
- 파이썬차트
- sql연습
- 팀플기록
- SQLSCOTT
- Python
- python수업
- python데이터분석
- 주피터노트북맷플롯립
- python알고리즘
- 주피터노트북그래프
- 데이터분석시각화
- 주피터노트북데이터분석
- 파이썬
- 수업기록
- 파이썬수업
- 파이썬시각화
- sql따라하기
- 주피터노트북
Archives
- Today
- Total
IT_developers
Python 개념 및 실습 - 파일 읽고 쓰기(1) 본문
화면 출력 print, 입력 input
open("파일명", 모드, encoding...) : 파일을 읽거나 쓸 때 사용
with + open() : close()를 알아서 해줌
f = open("data/test1.txt", "w", encoding="utf-8")
f.write("안녕하세요\n반갑습니다.")
f.close()
with open("data/test1.txt", "w", encoding="utf-8") as f:
f.write("안녕하세요\n반갑습니다.")
# 1~10까지 파일로 작성
# w : 기존에 있던 내용은 무시하고 새로 작성
f = open("data/test1.txt", "w", encoding="utf-8")
for i in range(1, 11):
f.write("%d\n" % i)
f.close()
with open("data/test1.txt", "a", encoding="utf-8") as f:
for i in range(1, 11):
f.write("%d\n" % i)

# a : append 기능. 기존에 있던 내용 뒤로 덧붙이기
f = open("data/test1.txt", "a", encoding="utf-8")
for i in range(1, 11):
f.write("%d\n" % i)
f.close()

# list를 파일에 쓰려면 for문 + write(), for문 + writelines()
# list를 파일로 작성
list = ["홍길동", "김길동", "최길동"]
f = open("data/test1.txt", "w", encoding="utf-8")
f.write(list) #TypeError: write() argument must be str, not list
f.close()
# writelines : 줄단위로 작성
list = ["홍길동", "김길동", "최길동"]
f = open("data/test1.txt", "w", encoding="utf-8")
f.writelines(list)
f.close()

list = ["홍길동\n", "김길동\n", "최길동\n"]
f = open("data/test1.txt", "w", encoding="utf-8")
f.writelines(list)
f.close()
list = ["홍길동", "김길동", "최길동"]
f = open("data/test1.txt", "w", encoding="utf-8")
for i in list:
f.write(i + "\n")
f.close()

# 딕셔너리 파일로 작성
dict1 = {"name": "hong", "age": 25, "addr": "서울"}
f = open("data/test1.txt", "w", encoding="utf-8")
# f.writelines(dict1) 키 값만 기록됨
for k, v in dict1.items():
f.writelines("{} : {}\n".format(k, v))
f.close()
# 실습 : 1000 명의 키와 몸무게를 랜덤으로 생성한 후 파일 작성
import random
list1 = list("가나다라마바사아자차카타파하")
f = open("data/info.txt", "w", encoding="utf-8")
# choice(list1) : 무작위로 하나
# randrange(40,100) : 40~100 사이 임의의 숫자
for i in range(1000):
name = random.choice(list1) + random.choice(list1)
weight = random.randrange(40, 100)
height = random.randrange(140, 200)
f.writelines("{}, {}, {}\n".format(name, weight, height))
f.close()
'Python' 카테고리의 다른 글
Python 개념 및 실습 - 파일 읽고 쓰기(3) (0) | 2022.09.10 |
---|---|
Python 개념 및 실습 - 파일 읽고 쓰기(2) (0) | 2022.09.09 |
Python 개념 및 실습 - 함수(2) (0) | 2022.09.08 |
Python 개념 및 실습 - 함수(1) (0) | 2022.09.08 |
Python 개념 및 실습 - set (0) | 2022.09.07 |
Comments