with open('a.txt','w') as f:
f.writelines(['hi\n','bye\n'])
f.write('hello\n')
!cat a.txt with open('a.txt','r') as f:
lines=f.readlines()
print(lines)with open('/content/sample_data/anscombe.json','r') as f:
print( f.readlines() )
# f.close()참고사항.
- with 를 쓰는 경우 close를 쓰지 않아도 알아서 닫아줍니다.
import os
from os.path import join,isfile,isdir
# dir(os.path)
# 'abspath','altsep','basename','commonpath','commonprefix','curdir','defpath','devnull',
# 'dirname','exists','expanduser','expandvars','extsep','genericpath','getatime','getctime',
# 'getmtime','getsize','isabs','isdir','isfile','islink','ismount','join','lexists','normcase',
# 'normpath','os','pardir','pathsep','realpath','relpath','samefile','sameopenfile','samestat',
# 'sep','split','splitdrive','splitext','stat','supports_unicode_filenames','sys'currentPath=os.getcwd()
print (os.getcwd()) #현재 디렉토리의
os.chdir("/")
print (os.getcwd()) #현재 디렉토리의
os.chdir(currentPath)
print (os.getcwd()) #현재 디렉토리의a_txt_path=join(currentPath,'a.txt')
a_txt_path
isfile(a_txt_path)isdir(currentPath)print(os.listdir(os.getcwd()))# 현재 작업 폴더 얻기,
os.getcwd()# 특정 경로에 대해 절대 경로 얻기,
os.path.abspath("./Scripts")# 경로 중 디렉토리명만 얻기,
currentPath=os.getcwd()
a_txt_path=join(currentPath,'a.txt')
os.path.dirname(a_txt_path)# 파일명을 얻기,
os.path.basename(a_txt_path)# "파일 각 경로를 나눠 리스트로 리턴하기,
os.path.split(a_txt_path)# os.path.sep은 OS별 경로 분리자",
a_txt_path.split(os.path.sep)# 디렉토리 안의 파일/서브디렉토리 리스트,
os.listdir(currentPath)# 파일 혹은 디렉토리 경로가 존재하는지 체크하기,
os.path.exists(a_txt_path), os.path.exists(currentPath)# 디렉토리 경로가 존재하는지 체크하기,
os.path.isdir(currentPath)# 파일 경로가 존재하는지 체크하기,
os.path.isfile(a_txt_path)# 파일의 크기,
!echo "1234">{a_txt_path}
os.path.getsize(a_txt_path)from pathlib import Path
parentPath=Path(basePath).parent
# join(os.path.abspath( join(basePath,"..") )
parentPathimport os
directory='/tmp/xx/yy'
if not os.path.exists(directory):
os.makedirs(directory)!ls /tmp/xximport os
import sys
from pathlib import Path
basePath=os.path.dirname(sys.argv[0])
childPath=os.path.join(basePath,"test")
os.makedirs(childPath)
print(os.listdir(basePath))
parentPath=Path(basePath).parent
# join(os.path.abspath( join(basePath,"..") )
executedPath=os.getcwd()
os.path.isdir(basePath)
os.path.isfile(basePath)