python -- file, 폴더 확인하기
환경 : windows 10 64bit, python 3.6 32bit
<< 지정한 폴더내부의 file, 디렉토리 목록 구하기 >>
>>> import os
>>> mypath = "C:/eBEST"
>>>
>>> print(os.listdir(mypath))
['Common', 'eBestPro', 'speddownlist.ini', 'Temp', 'xingAPI']
>>>
>>> for x in os.listdir(mypath):
if os.path.isfile(os.path.join(mypath, x)):
print("file ==> {0}".format(x))
if os.path.isdir(os.path.join(mypath, x)):
print("folder ==> {0}".format(x))
folder ==> Common
folder ==> eBestPro
file ==> speddownlist.ini
folder ==> Temp
folder ==> xingAPI
>>>
>>>
<< 폴더 경로구분자 '/', '\' 상광없이 인식하여, 경로포함 내부파일목록 가져오기 >>
** os.path.abspath() 를 사용한다.
import os | |
def fullpathfilename(mypath): | |
""" | |
디렉토리 경로 구분자 '/' , '\' 모두 인식하여, | |
전체경로포함한 디렉토리 내부 파일 목록 list 반환한다. | |
- 디렉토리는 제외한다. | |
""" | |
files = [] | |
# 디렉토리인지 확인하기 | |
if os.path.isdir(mypath): | |
resultpath = os.path.abspath(mypath) # 구분자 '/' , '\' 모두 인식 | |
for fname in os.listdir(resultpath): | |
fullname = os.path.join(resultpath, fname) | |
if os.path.isfile(fullname): | |
files.append(fullname) | |
return files | |
mypath = "C:/eBEST/Common" | |
mypath2 = "C:\eBEST\Common" | |
flist = fullpathfilename(mypath) | |
print(flist[:5]) | |
flist2 = fullpathfilename(mypath2) | |
print(flist2[:5]) |
<< os.sep 사용하기 >>
os.sep -- OS 에 상관없이 디렉토리 구분자 역할함.
>>> aa = "c:/stockdata2/"
>>>
>>> os.path.abspath(aa)
>>>
>>> os.sep
>>>
>>> os.path.abspath(aa) + os.sep + 'aa.txt'
<< 현재 실행파일의 path 알기 >>
dir = os.path.dirname(__file__)
print(dir)
'python' 카테고리의 다른 글
pyenv -- 설치가능한 python 확인하기 (0) | 2017.04.23 |
---|---|
pyenv upgrade 하기 (0) | 2017.04.22 |
jupyter notebook 사용법 (0) | 2017.04.18 |
Mac -- python 3.5 가상환경에서 numpy, scipy, matplotlib, pandas , jupyter 설치하기 (0) | 2016.08.18 |
python -- Mac 에서 pyenv, virtualenv 설치하기 (0) | 2016.05.02 |