Skip to content

Latest commit

 

History

History
260 lines (156 loc) · 3.36 KB

File metadata and controls

260 lines (156 loc) · 3.36 KB

기본 처리

파일 쓰기

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

with open('/content/sample_data/anscombe.json','r') as f:
  print( f.readlines() )
# f.close()

참고사항.

  • with 를 쓰는 경우 close를 쓰지 않아도 알아서 닫아줍니다.

Os Liberary로 처리

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'

cd,pwd

currentPath=os.getcwd()

print (os.getcwd()) #현재 디렉토리의

os.chdir("/")

print (os.getcwd()) #현재 디렉토리의


os.chdir(currentPath)
print (os.getcwd()) #현재 디렉토리의

join

a_txt_path=join(currentPath,'a.txt')
a_txt_path

isfile

isfile(a_txt_path)

isdir

isdir(currentPath)

ls

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)

pathlib.Path

from pathlib import Path
parentPath=Path(basePath).parent
# join(os.path.abspath( join(basePath,"..") )
parentPath

Mkdir

import os
directory='/tmp/xx/yy'
if not os.path.exists(directory):
    os.makedirs(directory)
!ls /tmp/xx

Examples

full example

import 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)