%%writefile 파일명.확장자 # 현재 주피터 노트북 파일의 경로에 파일 생성.
1st line # 파일 내 1번째 줄 내용
2nd line # 파일 내 2번째 줄 내용
# cell 내에
pwd # 입력 후 실행
변수 = open("파일명.확장자")
[Errno 2] No such file or directory: 'myfile2.txt'
# 파이썬이 '\'를 escape 문자로 인식하지 않도록 2번'\\' 사용
myfile = open("C:\\Users\\UserName\\Folder\\FileName.txt")
myfile = open("/Users/YouUserName/Folder/FileName.txt")
myfile.close()
myfile.read()
> '\n1st line\n2nd line\n3rd line\n'
myfile.read()
> ' ' # 커서의 위치가 제일 마지막에 있기 때문에 빈 문자열 출력
myfile.seek(0) # 커서를 0의 위치로 초기화
myfile.readlines()
> ['\n', '1st line\n', '2nd line\n', '3rd line\n']
with {expression} as {variable}:
block.. # 코드 블록 영역
# myfile.txt 파일을 열어 내용을 읽은(출력) 후 닫는다.
with open("myfile.txt",mode="a") as f:
f.read()
> 1st line
2nd line
3rd line
# myfile.txt 문서의 끝에 내용을 추가한다
with open("myfile.txt",mode="a") as f:
f.write("4rd line")
# myfile.txt 파일을 열어 내용을 읽은(출력) 후 닫는다.
with open("myfile.txt",mode="a") as f:
f.read()
> 1st line
2nd line
3rd line
4rd line
# wow.txt 파일을 생성하고 내용을 추가한다.
with open("wow.txt",mode="w") as f:
f.write("world\nof\nwarcraft\n")
# wow.txt 파일을 열어 내용을 읽은(출력) 후 닫는다.
with open("wow.txt",mode="r") as f:
print(f.read())
> world
of
warcraft