240911
파일 읽고 쓰기
- Path.home() : 홈 디렉터리 확인
In [23]:
# 홈 디렉터리
from pathlib import Path
print(Path.home())
C:\Users\User
- Path.cwd() : 현재 작업 디렉터리 확인
In [26]:
from pathlib import Path
print(Path.cwd())
C:\Users\User\Python
- Path.home().glob() : 디렉터리 안의 내용 확인
In [34]:
from pathlib import Path
files1 = Path.cwd().glob('*') # 모든 파일 및 폴더 검색
for f in files1:
print(f)
print()
files2 = Path.cwd().glob('*.txt') #모든 txt 파일 검색
for f in files2:
print(f)
파일 읽고 쓰기
- 'w' 쓰기
- 'r' 읽기
- 'a' 추가하기
- 'x' 파일 존재 시 오류 발생
In [72]:
f = open('filereview.txt', 'w') # 모드 'w', 'r', a', 'x'
f.write('hello\n')
f.close()
with open('filereview.txt', 'a') as f:
f.write('hello2')
file = open('filereview.txt', 'r')
s = file.readlines()
for x in s:
print(x, end = '')
f.close()
hello
hello2
- writelines()
- readlines()
In [83]:
f = open('greet.txt', 'w')
greet = ['안녕하세요', '반갑습니다', '사이좋게 지내요']
for ment in greet:
f.write(ment) # write()는 개행 하지 않음, print는 자동으로 개행
f.close()
f = open('greet.txt', 'r')
st = f.readlines()
print(st)
f.close()
['안녕하세요반갑습니다사이좋게 지내요']
In [87]:
f = open('greet.txt', 'w')
greet = ['안녕하세요\n', '반갑습니다\n', '사이좋게 지내요\n']
for ment in greet:
f.write(ment) # write()는 개행 하지 않음, print는 자동으로 개행
f.close()
f = open('greet.txt', 'r')
st = f.readlines()
for ment in st:
print(ment, end ='')
f.close()
안녕하세요
반갑습니다
사이좋게 지내요
In [93]:
f = open('greet.txt', 'w')
greet = ['안녕하세요\n', '반갑습니다\n', '사이좋게 지내요\n']
f.writelines(greet) # writelines로 한번에 쓰기
f.close()
f = open('greet.txt', 'r')
st = f.readlines()
for ment in st:
print(ment, end ='')
f.close()
안녕하세요
반갑습니다
사이좋게 지내요