리스트 합치기 질문 드립니다.
조회수 934회
import os
def search(dirname):
filenames = os.listdir(dirname)
for filename in filenames:
full_filename = os.path.join(filename)
ext = os.path.splitext(full_filename)[-1]
if ext == '.py' or ext == '.txt':
print([full_filename])
search("C:/Users/Administrator/PycharmProjects/untitled")
이코드를 출력하면 확장자가 .py .txt인 파일을 출력하는데 궁금한게 있습니다 따로따로 출력말고 리스트 안에 전부 넣고싶은데 어떤 방법을 이용해야하나요?
['xxx.py']
['xxxx.py']
['xx.txt']
.
.
이렇게 말고
['xxx.py','xxxx.py','xx.txt']
이렇게 할려면 List comprehension 방식을 사용해야하는지 궁금합니다.
2 답변
-
반복문 밖에서 full_filename 을 담을 수 있는 리스트를 하나 선언하고,
if ext == '.py' or ext == '.txt':
조건문 안에서 full_filename을 리스트에 append 한 후 반복문 종료 후 리스트를 출력하시면 될 것 같습니다.append 튜토리얼 입니다.
-
[f for f in os.listdir('/home/allinux/workspace/PyRFC-1.9.6') if f.endswith('.py')] Out[16]: ['sitecustomize.py', 'setup.py']
list comprehension 을 이용하면 편하게 할 수 있습니다.
댓글 입력