import os
print(os.getcwd())
/Users/yhhan/git/supercharged_python
print(os.listdir(), len(os.listdir()))
['13. 넘파이 고급 사용법.ipynb', 'assignment2021', 'tables_skill_up', 'python-e-learning', 'stuff.txt', '14. 여러 모듈과 RPN 예시.ipynb', '16. 부록 A_B.ipynb', '09. 클래스와 매직 메서드.ipynb', '.DS_Store', '11. Random과 Math 패키지.ipynb', '18. 부록 D.ipynb', 'r.py', '01. 파이썬 기초 돌아보기.ipynb', '20. 부록 F.예외 다루기.ipynb', 'images', 'example', '19. 부록 E.ipynb', '17. 부록 C.ipynb', 'stock_plot_v2.py', 'team_data.txt', 'images_skill_up', '04. 지름길, 커맨드 라인 그리고 패키지.ipynb', 't_copied.txt', 'rpn.txt', '__pycache__', 'stock_plot_v3.py', '08. 텍스트와 바이너리 파일.ipynb', 'README.md', 't.txt', 'stock_plot_v4.py', '.gitignore', '06. 정규 표현식, 파트 1.ipynb', '15. 인터넷에서 금융 데이터 가져오기.ipynb', 'stock_plot_v1.py', 'readme.txt', '07. 정규 표현식, 파트 2.ipynb', '.ipynb_checkpoints', '05. 정밀하게 텍스트 포매팅하기.ipynb', '.git', 'rpn2.txt', '12. 넘파이 패키지.ipynb', '10. 십진수, 돈 그리고 기타 클래스.ipynb', '03. 고급 리스트 기능.ipynb', '02. 고급 문자열 기능.ipynb', 'stock_demo.py', 'stock_load.py', '.idea'] 47
os.mkdir("my_dir")
print(os.listdir(), len(os.listdir()))
['13. 넘파이 고급 사용법.ipynb', 'assignment2021', 'tables_skill_up', 'python-e-learning', 'stuff.txt', '14. 여러 모듈과 RPN 예시.ipynb', '16. 부록 A_B.ipynb', '09. 클래스와 매직 메서드.ipynb', '.DS_Store', '11. Random과 Math 패키지.ipynb', '18. 부록 D.ipynb', 'r.py', '01. 파이썬 기초 돌아보기.ipynb', '20. 부록 F.예외 다루기.ipynb', 'images', 'example', '19. 부록 E.ipynb', '17. 부록 C.ipynb', 'stock_plot_v2.py', 'team_data.txt', 'images_skill_up', '04. 지름길, 커맨드 라인 그리고 패키지.ipynb', 't_copied.txt', 'rpn.txt', '__pycache__', 'stock_plot_v3.py', '08. 텍스트와 바이너리 파일.ipynb', 'README.md', 't.txt', 'stock_plot_v4.py', '.gitignore', '06. 정규 표현식, 파트 1.ipynb', '15. 인터넷에서 금융 데이터 가져오기.ipynb', 'stock_plot_v1.py', 'readme.txt', '07. 정규 표현식, 파트 2.ipynb', '.ipynb_checkpoints', '05. 정밀하게 텍스트 포매팅하기.ipynb', '.git', 'rpn2.txt', '12. 넘파이 패키지.ipynb', '10. 십진수, 돈 그리고 기타 클래스.ipynb', '03. 고급 리스트 기능.ipynb', '02. 고급 문자열 기능.ipynb', 'stock_demo.py', 'stock_load.py', 'my_dir', '.idea'] 48
print(os.path.isfile("stock_load.py"))
True
print(os.path.isfile("my_dir"))
False
print(os.path.isdir("my_dir"))
True
print(os.path.join("my_dir", "sub_dir_1", "sub_dir_2"))
my_dir/sub_dir_1/sub_dir_2
f = open(fname, 'r')
Mode | 간단 설명 | 자세한 설명 |
---|---|---|
'r' | 읽기 전용(기본 모드) | 파일 객체를 읽기 모드로 생성하고, 파일 포인터를 파일 처음 위치에 놓는다. |
'w' | 쓰기 전용(기존 파일 내용 삭제) | 파일이 존재하지 않으면 새로운 파일을 쓰기 모드로 생성하고, 해당 파일이 이미 존재하면 내용을 모두 없에면서 쓰기 모드로 생성하고, 파일 포인터를 파일 처음 위치에 놓는다. |
'a' | 파일 끝에 추가(쓰기 전용) | 파일이 존재하지 않으면 새롭게 파일을 생성하면서 쓰기 모드로 생성하고, 해당 파일이 이미 존재하면 파일 객체을 쓰기 모드로 생성하면서 파일 포인터를 파일의 마지막 위치에 놓는다. 따라서, 이후 작성되는 내용은 파일의 뒷 부분에 추가됨. |
'r+' | 읽고 쓰기 | 파일 객체를 읽고 쓸 수 있도록 생성한다. 파일 포인터를 파일 처음 위치에 놓는다. |
'w+' | 읽고 쓰기(기존 파일 내용 삭제) | 파일 객체를 읽고 쓸 수 있도록 생성한다. 파일이 존재하지 않으면 새로운 파일을 생성하고, 해당 파일이 이미 존재하면 내용을 모두 없에면서 생성하고, 파일 포인터를 파일 처음 위치에 놓는다. |
'a+' | 읽고 쓰기(파일 끝에 추가) | 파일 객체를 읽고 쓸 수 있도록 생성한다. 파일이 존재하지 않으면 새롭게 파일을 생성하고, 해당 파일이 이미 존재하면 파일 객체을 생성하면서 파일 포인터를 파일의 마지막 위치에 놓는다 (그래서, 이후 작성되는 내용은 파일의 뒷 부분에 추가). |
try:
fname = input('Enter file to read:')
f = open(fname, 'r')
print(f.read())
except FileNotFoundError:
print('File', fname, 'not found. Terminating.')
Enter file to read:stock_load.py '''File stock_load.py ----------------------------- 주식 시세(ticker) 기호를 가져오기 위해서 주식 적재 작업을 수행한다. 의존하고 있는 모듈은 없다. ''' # pip install pandas_datareader import pandas_datareader.data as web def load_stock(ticker_str): ''' 주식 적재 함수. 인수로 주어진 문자열 ticker_str의 정보를 적재한다. 'MSFT'와 같이 정해진 주식의 정보를 pandas 데이터 프레임에 넣고 반환한다. ''' df = web.DataReader(ticker_str, 'yahoo') df = df.reset_index() return df # 데이터 프레임(stock_df)을 가져와서 출력한다. if __name__ == '__main__': stock_df = load_stock('MSFT') # 'msft'를 입력해도 괜찮다. print(stock_df) print(stock_df.columns)
while True:
try:
fname = input('Enter file name: ')
if not fname: # 빈 문자열이 입력되면 종료한다.
break
f = open(fname) # 파일 열기를 시도한다.
print(f.read())
f.close()
break
except FileNotFoundError:
print('File could not be found. Re-enter.')
while True:
fname = input('Enter file name: ')
if not fname:
break
try:
f = open(fname) # 파일 열기를 시도한다.
except FileNotFoundError:
print('File could not be found. Re-enter.')
else:
print(f.read())
f.close()
break
with open('stock_load.py', 'r') as f:
lst = f.readlines()
for thing in lst:
print(thing, end='')
'''File stock_load.py ----------------------------- 주식 시세(ticker) 기호를 가져오기 위해서 주식 적재 작업을 수행한다. 의존하고 있는 모듈은 없다. ''' # pip install pandas_datareader import pandas_datareader.data as web def load_stock(ticker_str): ''' 주식 적재 함수. 인수로 주어진 문자열 ticker_str의 정보를 적재한다. 'MSFT'와 같이 정해진 주식의 정보를 pandas 데이터 프레임에 넣고 반환한다. ''' df = web.DataReader(ticker_str, 'yahoo') df = df.reset_index() return df # 데이터 프레임(stock_df)을 가져와서 출력한다. if __name__ == '__main__': stock_df = load_stock('MSFT') # 'msft'를 입력해도 괜찮다. print(stock_df) print(stock_df.columns)
with open('file.txt', 'w') as f:
f.write('To be or not to be\n')
f.write('That is the question.\n')
f.write('Whether tis nobler in the mind\n')
f.write('To suffer the slings and arrows\n')
with open('file.txt', 'r') as f:
print(f.read())
To be or not to be That is the question. Whether tis nobler in the mind To suffer the slings and arrows
with open('file.txt', 'r') as f:
s = ' ' # 빈 칸으로 초기화한다.
while s:
s = f.readline()
print(s)
To be or not to be That is the question. Whether tis nobler in the mind To suffer the slings and arrows
with open('file.txt', 'r') as f:
s = ' ' # 빈 칸으로 초기화한다.
while s:
s = f.readline()
s = s.rstrip('\n')
print(s)
To be or not to be That is the question. Whether tis nobler in the mind To suffer the slings and arrows
with open('file.txt', 'r') as f:
str_list = f.readlines()
for s in str_list:
print(s, end='')
To be or not to be That is the question. Whether tis nobler in the mind To suffer the slings and arrows
f.seek(pos, orig)
f.tell()
with open('file.txt', 'r') as f:
print(f.seekable())
print(f.read(5))
print(f.tell())
print("*" * 80)
f.seek(0, 0)
print(f.tell())
print(f.read(5))
True To be 5 ******************************************************************************** 0 To be
with open('my.dat', 'wb') as f:
b = b'\x01\x02\x03\x0f\x10\x1f'
print(type(b))
f.write(b)
b = b'hello'
print(type(b))
f.write(b)
<class 'bytes'> <class 'bytes'>
print(os.listdir())
['13. 넘파이 고급 사용법.ipynb', 'assignment2021', 'file.txt', 'tables_skill_up', 'python-e-learning', 'stuff.txt', '14. 여러 모듈과 RPN 예시.ipynb', '16. 부록 A_B.ipynb', '09. 클래스와 매직 메서드.ipynb', '.DS_Store', '11. Random과 Math 패키지.ipynb', '18. 부록 D.ipynb', 'r.py', '01. 파이썬 기초 돌아보기.ipynb', '20. 부록 F.예외 다루기.ipynb', 'images', 'example', '19. 부록 E.ipynb', '17. 부록 C.ipynb', 'stock_plot_v2.py', 'team_data.txt', 'images_skill_up', '04. 지름길, 커맨드 라인 그리고 패키지.ipynb', 't_copied.txt', 'rpn.txt', '__pycache__', 'stock_plot_v3.py', '08. 텍스트와 바이너리 파일.ipynb', 'README.md', 't.txt', 'stock_plot_v4.py', '.gitignore', '06. 정규 표현식, 파트 1.ipynb', '15. 인터넷에서 금융 데이터 가져오기.ipynb', 'stock_plot_v1.py', 'readme.txt', '07. 정규 표현식, 파트 2.ipynb', '.ipynb_checkpoints', '05. 정밀하게 텍스트 포매팅하기.ipynb', '.git', 'rpn2.txt', '12. 넘파이 패키지.ipynb', '10. 십진수, 돈 그리고 기타 클래스.ipynb', '03. 고급 리스트 기능.ipynb', '02. 고급 문자열 기능.ipynb', 'stock_demo.py', 'stock_load.py', 'my_dir', 'my.dat', '.idea']
with open('my.dat', 'rb') as f:
bss = f.read()
print(type(bss), len(bss))
for i in bss:
print(i, end=' ')
<class 'bytes'> 11 1 2 3 15 16 31 104 101 108 108 111
import pickle
with open('goo.dat', 'wb') as f:
pickle.dump([1, 2, 3], f)
pickle.dump('Hello!', f)
pickle.dump(3.141592, f)
with open('goo.dat', 'rb') as f:
a = pickle.load(f)
b = pickle.load(f)
c = pickle.load(f)
print(type(a), a)
print(type(b), b)
print(type(c), c)
<class 'list'> [1, 2, 3] <class 'str'> Hello! <class 'float'> 3.141592
if type(a) == list:
print('The length of a is {0}'.format(len(a)))
The length of a is 3
loaded = []
with open('goo.dat', 'rb') as f:
while True:
try:
item = pickle.load(f)
except EOFError:
print('Loaded', len(loaded), 'items.')
break
print(type(item), item)
loaded.append(item)
<class 'list'> [1, 2, 3] <class 'str'> Hello! <class 'float'> 3.141592 Loaded 3 items.
(생략)
import os
print(os.listdir('.')) # 현재 디렉토리의 파일 목록 얻기
print()
print(os.listdir('../')) # 현재 디렉토리의 부모 디렉토리의 파일 목록 얻기
['13. 넘파이 고급 사용법.ipynb', 'assignment2021', 'file.txt', 'tables_skill_up', 'python-e-learning', 'stuff.txt', '14. 여러 모듈과 RPN 예시.ipynb', '16. 부록 A_B.ipynb', '09. 클래스와 매직 메서드.ipynb', '.DS_Store', '11. Random과 Math 패키지.ipynb', '18. 부록 D.ipynb', 'r.py', '01. 파이썬 기초 돌아보기.ipynb', '20. 부록 F.예외 다루기.ipynb', 'images', 'example', '19. 부록 E.ipynb', '17. 부록 C.ipynb', 'stock_plot_v2.py', 'team_data.txt', 'images_skill_up', '04. 지름길, 커맨드 라인 그리고 패키지.ipynb', 't_copied.txt', 'rpn.txt', '__pycache__', 'stock_plot_v3.py', '08. 텍스트와 바이너리 파일.ipynb', 'README.md', 't.txt', 'stock_plot_v4.py', '.gitignore', '06. 정규 표현식, 파트 1.ipynb', '15. 인터넷에서 금융 데이터 가져오기.ipynb', 'stock_plot_v1.py', 'goo.dat', 'readme.txt', '07. 정규 표현식, 파트 2.ipynb', '.ipynb_checkpoints', '05. 정밀하게 텍스트 포매팅하기.ipynb', '.git', 'rpn2.txt', '12. 넘파이 패키지.ipynb', '10. 십진수, 돈 그리고 기타 클래스.ipynb', '03. 고급 리스트 기능.ipynb', '02. 고급 문자열 기능.ipynb', 'stock_demo.py', 'stock_load.py', 'my_dir', 'my.dat', '.idea'] ['unity', 'python-e-learning', 'hands_on_ml_link', 'deeplink_public', 'crypto', 'auto_trading', 'web-apps-node-iot-hub-data-visualization.zip', 'rl_sortation', '.DS_Store', 'CsvReader.py', 'e_learning_rl_old', 'pwd', 'link_home', 'manuscriptlink', 'introduction_to_ml_with_python', 'ccxt', 'papers', '4thIR', 'out', 'starcraft2', 'trade', 'mxnet', 'gym-minigrid', 'test_world', 'web-old', 'link_rl_book_codes', 'supercharged_python', 'link_marl', 'link_rl', 'trade_rl', 'e_learning_rl', 'flask_rest', 'link_rl_book', 'auto_trading_old', 'tf_15', 'betcentrality', 'openshs', 'DeepRL', 'SparceReward', 'crawl', 'rotary_pendulum', '.gitignore', 'd2l-en', 'web-apps-node-iot-hub-data-visualization', 'link_vne', 'link_rl_book_old_latex_with_codes', 'paper_writings', 'VirtualDevice.py', '.git', 'or', 'journalhome', 'minimal_rl', 'ktccs-ktsde-website', 'etri-ksb', 'deeplink', 'rl', 'invest', 'upbit_auto_trade']
import os
def filetype(fpath):
print(fpath, ':', end="")
if os.path.isfile(fpath):
print('Regular file')
if os.path.isdir(fpath):
print('Directory')
if os.path.islink(fpath):
print('Symbolic link')
flist = os.listdir('.')
for fname in flist:
filetype(fname)
13. 넘파이 고급 사용법.ipynb :Regular file assignment2021 :Directory file.txt :Regular file tables_skill_up :Directory python-e-learning :Directory stuff.txt :Regular file 14. 여러 모듈과 RPN 예시.ipynb :Regular file 16. 부록 A_B.ipynb :Regular file 09. 클래스와 매직 메서드.ipynb :Regular file .DS_Store :Regular file 11. Random과 Math 패키지.ipynb :Regular file 18. 부록 D.ipynb :Regular file r.py :Regular file 01. 파이썬 기초 돌아보기.ipynb :Regular file 20. 부록 F.예외 다루기.ipynb :Regular file images :Directory example :Directory 19. 부록 E.ipynb :Regular file 17. 부록 C.ipynb :Regular file stock_plot_v2.py :Regular file team_data.txt :Regular file images_skill_up :Directory 04. 지름길, 커맨드 라인 그리고 패키지.ipynb :Regular file t_copied.txt :Regular file rpn.txt :Regular file __pycache__ :Directory stock_plot_v3.py :Regular file 08. 텍스트와 바이너리 파일.ipynb :Regular file README.md :Regular file t.txt :Regular file stock_plot_v4.py :Regular file .gitignore :Regular file 06. 정규 표현식, 파트 1.ipynb :Regular file 15. 인터넷에서 금융 데이터 가져오기.ipynb :Regular file stock_plot_v1.py :Regular file goo.dat :Regular file readme.txt :Regular file 07. 정규 표현식, 파트 2.ipynb :Regular file .ipynb_checkpoints :Directory 05. 정밀하게 텍스트 포매팅하기.ipynb :Regular file .git :Directory rpn2.txt :Regular file 12. 넘파이 패키지.ipynb :Regular file 10. 십진수, 돈 그리고 기타 클래스.ipynb :Regular file 03. 고급 리스트 기능.ipynb :Regular file 02. 고급 문자열 기능.ipynb :Regular file stock_demo.py :Regular file stock_load.py :Regular file my_dir :Directory my.dat :Regular file .idea :Directory
s = """Its power: Python developers typically report
they are able to develop applications in a half
to a tenth the amount of time it takes them to do
the same work in such languages as C."""
with open('t.txt', 'w') as f:
f.write(s) # 문자열을 파일에 기록
import os
os.rename('t.txt', 't1.txt') # t.txt를 t1.txt로 바꾼다
os.mkdir('example')
os.rename('t1.txt', './example/t1.txt') # 현재 작업 디렉토리의 t1.txt를 example에 t1.txt이름으로 옮긴다.
import shutil
s = """Its power: Python developers typically report
they are able to develop applications in a half
to a tenth the amount of time it takes them to do
the same work in such languages as C."""
with open('t.txt', 'w') as f:
f.write(s) # 문자열을 파일에 기록
shutil.copyfile('t.txt', 't_copied.txt')
't_copied.txt'
import os
print(os.path.abspath('o.txt'))
/Users/yhhan/git/supercharged_python/o.txt
f = '/Users/yhhan/git/python-e-learning/sample.txt'
print(os.path.exists(f))
print(os.path.exists('sample.txt'))
print(os.path.exists('asdf.txt'))
False False False
print(os.curdir) #현재 디렉토리
print(os.pardir) #부모 디렉토리
. ..
print(os.sep)
/
f = '/Users/yhhan/git/python-e-learning/t.txt'
print(os.path.basename(f)) # 파일명만 추출
print(os.path.dirname(f)) # 디렉토리 경로 추출
t.txt /Users/yhhan/git/python-e-learning
print(os.path.split(f))
('/Users/yhhan/git/python-e-learning', 't.txt')
print(os.path.splitdrive(f))
('', '/Users/yhhan/git/python-e-learning/t.txt')
print(os.path.splitext(f))
('/Users/yhhan/git/python-e-learning/t', '.txt')
path = os.path.join("/", "Users", "yhhan", "git", "python-e-learning", "t.txt")
print(path)
/Users/yhhan/git/python-e-learning/t.txt
path = os.path.join("c:\\", "Users", "yhhan")
print(path)
c:\/Users/yhhan
import os
print(os.getcwd())
/Users/yhhan/git/supercharged_python
path = os.path.join("/", "Users", "yhhan", "Public")
#path = os.path.join("c:\\", "Users", "yhhan", "Public")
os.chdir(path)
print(os.getcwd())
/Users/yhhan/Public
import os
os.mkdir('temp_new') # 0755 기본 모드(rwxr-xr-x)로 만들어짐
%ls -al temp_new
# os.mkdir('temp2', 0700) # 0700 모드(rwx------)로 만들어짐
os.mkdir('temp_new_2', 0o700)
os.makedirs('temp_new_2/level1/level2') #0755 기본 모드, 중간에 필요한 디렉토리도 모두생성
--------------------------------------------------------------------------- FileExistsError Traceback (most recent call last) <ipython-input-26-75c8a2e656f5> in <module> 1 import os 2 ----> 3 os.mkdir('temp_new') # 0755 기본 모드(rwxr-xr-x)로 만들어짐 4 5 get_ipython().run_line_magic('ls', '-al temp_new') FileExistsError: [Errno 17] File exists: 'temp_new'
import os
os.mkdir('temp3', 0o700)
path = os.path.join("temp3", "level1", "level2")
os.makedirs(path) #0755 기본 모드, 중간에 필요한 디렉토리도 모두생성
os.rmdir('temp') #디렉토리에 내용이 없을 때 삭제가능
--------------------------------------------------------------------------- OSError Traceback (most recent call last) <ipython-input-28-54fceefd86e5> in <module> ----> 1 os.rmdir('temp') #디렉토리에 내용이 없을 때 삭제가능 OSError: [Errno 66] Directory not empty: 'temp'
os.rmdir('temp3') #디렉토리에 다른 파일이 있으면 삭제할 수 없음
--------------------------------------------------------------------------- OSError Traceback (most recent call last) <ipython-input-29-4a5a038b13f9> in <module> ----> 1 os.rmdir('temp3') #디렉토리에 다른 파일이 있으면 삭제할 수 없음 OSError: [Errno 66] Directory not empty: 'temp3'
os.removedirs('temp2/level1/level2')
--------------------------------------------------------------------------- FileNotFoundError Traceback (most recent call last) <ipython-input-30-009b0f54d4dd> in <module> ----> 1 os.removedirs('temp2/level1/level2') ~/anaconda3/lib/python3.6/os.py in removedirs(name) 236 237 """ --> 238 rmdir(name) 239 head, tail = path.split(name) 240 if not tail: FileNotFoundError: [Errno 2] No such file or directory: 'temp2/level1/level2'