[파이썬] os 디렉토리, 파일 컨트롤¶
In [1]:
from IPython.core.display import display, HTML
display(HTML("<style>.container{width:90%!important;}</style>"))
In [2]:
import os
목차¶
간략설명¶
- os는 경로 내 파일 확인, 디렉토리(폴더/direction, 이하 디렉토리) 만들기 등 디렉토리 및 파일을 컨트롤 하기 위해 사용됩니다.
- 처음 파이썬 코드를 공부할때 많이 사용되지 않았지만 코드를 짜는 경력이 길어 질수록 많이 사용 합니다.
[참고] os와 shutil을 설명하기 위한 파일 및 디렉토리를 만드는 코드입니다. 우선 본 코드를 실행 시키신 후 아래 코드를 이해하시면 더 아래 내용을 더 효율적으로 이해할 수 있습니다.
In [3]:
os.makedirs("os_example", exist_ok=True)
with open("os_example/test1.txt", "w") as f:
f.write("Hello world !")
with open("os_example/test2.txt", "w") as f:
f.write("BE HAPPY !")
with open("os_example/test_csv.csv", "w") as f:
f.write("name," + "age,"+ "gender\n" )
f.write("Jain," + "21," + "Female\n")
f.write("Mark," + "25," + "Male")
- 위 코드를 실행 시키고 파일 탐색기(Finder)를 보시면 아래 그림처럼 "os_example" 디렉토리와 디렉토리 안레 "test" 파일 3가지 가 생성되었음을 볼 수 있습니다.
os.listdir경로 아래 디렉토리명 및 파일 이름을 리스트 형태로 반환하기¶
In [4]:
# os.listdir
path = "os_example/"
file_list = os.listdir(path)
file_list = [name for name in file_list if name[0] != "." ] # 숨김파일 제외
file_list
Out[4]:
['test_csv.csv', 'test1.txt', 'test2.txt']
In [5]:
# 1일 포함된 파일 이름 가져오기
[name for name in file_list if "1" in name]
Out[5]:
['test1.txt']
os.makedirs 새로운 디렉토리 만들기¶
In [6]:
# "directory_sample" 디렉토리 만들기
os.makedirs("os_example/directory_sample")
In [7]:
# "directory_sample" 추가 확인
for name in os.listdir(path):
if name[0] != ".": # 숨김파일 제외
if name == "directory_sample":
print('\033[31m' + name + '\033[0m')
else:
print(name)
test_csv.csv
test1.txt
test2.txt
directory_sample
os.makedirs에서 exist_ok 라는 옵션을 설정하지 않으면 같은 이름의 디렉토리가 있는 경우 에러가 출력 됩니다.
In [8]:
os.makedirs("os_example/directory_sample")
--------------------------------------------------------------------------- FileExistsError Traceback (most recent call last) <ipython-input-8-d964e45eff52> in <module> ----> 1 os.makedirs("os_example/directory_sample") /opt/anaconda3/lib/python3.8/os.py in makedirs(name, mode, exist_ok) 221 return 222 try: --> 223 mkdir(name, mode) 224 except OSError: 225 # Cannot rely on checking for EEXIST, since the operating system FileExistsError: [Errno 17] File exists: 'os_example/directory_sample'
그래서, "exist_ok=True" 라는 옵션을 지정해줘야 똑같은 디렉토리가 있는 경우 새로 만들지 않고 에러없이 넘어 갑니다.
In [9]:
os.makedirs("os_example/directory_sample", exist_ok=True)
os.path.join "/", "\" 등 분기처리를 무시하고 경로를 작성할 수 있는 사용¶
In [10]:
os.path.join("os_example", "directory_sample")
Out[10]:
'os_example/directory_sample'
In [11]:
os.path.join("os_example", "test1.txt")
Out[11]:
'os_example/test1.txt'
In [12]:
# os.path.join을 사용해서 "directory_sample" 폴더 안에 "test3.txt" 파일 만들기
with open(os.path.join("os_example", "directory_sample", "test3.txt"), "w") as f:
f.write("welcome to my house")
shutil.rmtree를 사용하여 디렉토리 지우기¶
- os 패키지 또한 "os.rmdir" 이라는 디렉토리 삭제 함수를 가지고 있지만 지우고자 하는 디렉토리 안에 파일이 있다면 삭제가 되지 않습니다.
In [13]:
os.rmdir(os.path.join("os_example", "directory_sample"))
--------------------------------------------------------------------------- OSError Traceback (most recent call last) <ipython-input-13-a5339542c0a8> in <module> ----> 1 os.rmdir(os.path.join("os_example", "directory_sample")) OSError: [Errno 66] Directory not empty: 'os_example/directory_sample'
- shutil.rmtree를 사용하여 파일과 디렉토리를 모두 삭제할 수 있다.
In [14]:
import shutil
shutil.rmtree(os.path.join("os_example", "directory_sample"))
os.path.isfile 제안된 경로에서 파일이 있는지 확인¶
In [15]:
# 파일이 있는 경우
suggested_path1 = "os_example/test1.txt"
os.path.isfile(suggested_path1)
Out[15]:
True
In [16]:
# 파일이 없는 경우
suggested_path2 = "os_example/direction_sample"
os.path.isfile(suggested_path2)
Out[16]:
False
In [17]:
# os.path.basename 추가하여 파일 명만 얻기
if os.path.isfile(suggested_path1):
print(os.path.basename(suggested_path1))
test1.txt
os.path.splitext 파일이름과 확장자를 구분하기¶
In [18]:
file_name, file_extension = os.path.splitext("test1.txt")
file_name, file_extension
Out[18]:
('test1', '.txt')
In [19]:
# os_example 디렉토리 안 모든 파일에 대한 적용
for name in file_list:
file_name, file_extension = os.path.splitext(name)
print("파일 이름 + 확장자: ", name)
print("파일 이름: ", file_name)
print("파일 확장자: ", file_extension)
print(" ")
파일 이름 + 확장자: test_csv.csv 파일 이름: test_csv 파일 확장자: .csv 파일 이름 + 확장자: test1.txt 파일 이름: test1 파일 확장자: .txt 파일 이름 + 확장자: test2.txt 파일 이름: test2 파일 확장자: .txt
In [20]:
# os_example 내 확장자가 csv 인것만 보여주기
for name in file_list:
file_name, file_extension = os.path.splitext(name)
if "csv" in file_extension:
print(name)
test_csv.csv
'코딩 > python' 카테고리의 다른 글
varimax_spss_example (0) | 2021.03.19 |
---|---|
Varimax_Rotation_and_Thereafter (0) | 2021.03.18 |
댓글