파일 읽기

With 문과 함께 사용하기
들여쓰기를 사용해 들여쓰기가 있는 코드에서는 open()함수가 유지
as문을 사용하여 변수에 할당

with open("dream.txt", "r") as my_file:
     contents = my_file.read()
     print(type(contents), contents)

한 줄씩 읽어 리스트형으로 반환
readlines() 메서드 사용
한줄의 기준 n으로 구분

with open("dream.txt", "r") as my_file:
     content_list = my_file.readlines()
     print(type(content_list))
     print(content_list)
with open("dream.txt", "r") as my_file:
     i=0
      while 1:
     line = my_file.readline()
     if not line:
      break
     print(str(i)+" === " +line.replace("n", "")
     i = i+1

인코딩 방식의 지정이 필요

f= open("count_log.txt",'w', encoding = "utf8")
For i in range(1,11):
      date = "%d번째 줄이다.n"%i
      f.write(date) 
f.close()

f= open(“count_log.txt”,’as’, encoding = “utf8”)as f:
For i in range(1,11):
date = “%d번째 줄이다.n”%i
f.write(date)

디렉토리 생성
파이썬 내에서 os모듈을 사용하여 폴더 구조도 함께 다룰 수 있음
import os
os.mkdir(“log”)

동일한 이름의 디렉토리 생성은 오류가 나는 부분에 따라 존재 여부를 확인
import os
os.mkdir(“log”)

if not os.path.isdir(“log”)
os.mkdir(“log”)

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post

Top SEO Tips For 2026 — Whiteboard Friday

Next Post

CognitoFlow vs. AutomatePrime: An Unflinching, API-First Comparison

Related Posts