# 파일 open
my_file = open("./test.txt", "w") # w: write 모드
# 텍스트 기입
str_cnt = my_file.write("Hello world!")
print("글자수:", str_cnt) # 글자수: 12
# 파일 close
my_file.close()
# test.txt
# 나의 이름은 홍길동.
# 나의 나이는 23세.
my_file = open("./test.txt")
content = my_file.read()
print(content)
my_file.close()
# 출력결과
# 나의 이름은 홍길동.
# 나의 나이는 23세.
my_file = open("./test.txt", "w")
my_file.write("abc")
my_file.write("\n")
my_file.write("def")
my_file.close()
# 저장결과
abc
def
with open('./test.txt', mode='w') as f:
f.write('abc\ndef') # 자동 close() 기능 포함
# 저장결과
abc
def
# test.txt
abc
def
xyz
# read() 시
with open("test.txt", "r") as f:
print(f.read())
# 출력예시
# abc
# def
# xyz
# readline() 시
with open("test.txt", "r") as f:
print(f.readline())
# 출력예시
# abc
# readlines() 시
with open("test.txt", "r") as f:
print(f.readlines())
# 출력예시
# ['abc\n', 'def\n', 'xyz\n']
my_list = ['abc\n', 'def\n', 'xyz\n']
# write() 사용 시
with open("./test.txt", "w) as f:
for elem in my_list:
f.write(elem)
# writelines() 사용 시
with open("./test.txt", "w) as f:
f.writelines(my_list)
# 저장결과(동일)
abc
def
xyz
*이 글은 제로베이스 데이터 취업 스쿨의 강의 자료 일부를 발췌하여 작성되었습니다.