Python
2014.05.20 14:18

Python 유용한 코드 모음

조회 수 15102 댓글 0
?

단축키

Prev이전 문서

Next다음 문서

+ - Up Down Comment Print
?

단축키

Prev이전 문서

Next다음 문서

+ - Up Down Comment Print
http://sweeper.egloos.com/m/3043544


1. 경로의 모든 하위 디렉토리 검색

  1. # os.walk를 이용한 방식이 젤 간단하고 빠르다.
  2. for root, sub_dirs, files in os.walk(path):
  3.     # 모든 파일에 대해...
  4.     for fname in files:
  5.         # 특정 확장자인 경우 (os.path.splitext 함수 좋다)
  6.         ext = (os.path.splitext(fname)[-1]).lower()
  7.             if ext == ".vcxproj":


2. 특정 디렉토리의 파일 리스트

  1. import glob
  2.  
  3. # C:/Python/ 디렉토리의 모든 파일 목록
  4. list = glob.glob("C:/Python/*")
  5.  
  6. # C:/Python/ 디렉토리의 Q로 시작하는 파일 목록
  7. list = glob.glob("C:/Python/Q*")
  8.  
  9. # C:/Python/ 디렉토리의 확장자 .py 파일 목록
  10. list = glob.glob("C:/Python/*.py")


3. 리스트 랜덤 셔플

  1. # sorted - element가 정수형일 때
  2. import os
  3.  
  4. list = [1,2,3,4,5]
  5. # sorted 함수는 셔플된 리스트를 반환, 원래 리스트는 변경하지 않는다
  6. list = sorted(list, key=os.urandom)
  7.  
  8. # sorted - element가 user-defined 타입일 때
  9. import random
  10.  
  11. class Test:
  12.     def __init__(self, id):
  13.         self.id = id
  14.  
  15. = Test(1)
  16. = Test(2)
  17. = Test(3)
  18. list = [a,b,c]
  19.  
  20. list = sorted(list, key=lambda *args: random.random())
  21.  
  22. # random.shuffle() - 모든 타입 가능, random.shuffle이 젤 나은 듯
  23. import random
  24.  
  25. list = [1,2,3,4,5]
  26. # random의 shuffle 함수는 반환값이 없고, 리스트 자체를 변경한다.
  27. random.shuffle(list)


4. int / int = float?

파이썬의 경우 정수를 정수로 나누면 그 결과가 정수형이 되는데,
이를 실수형으로 반환하고 싶을 때 아래와 같이 __future__ 모듈의 division 기능을 임포트하면 된다.

  1. # 정수형을 정수형으로 나눈 결과를 실수형으로
  2. # __future__ 모듈의 division 함수 임포트
  3. from __future__ import division
  4. = 5/2         # c = 2.5


5. swap

  1. = 1
  2. = 2
  3.  
  4. # swap
  5. a,= b,a


6. XML 인덴트 강제 조정

  1. def apply_indent(elem, level = 0):
  2.     # tab = space * 2
  3.     indent = "\n" + level * "  "
  4.     if len(elem):
  5.         if not elem.text or not elem.text.strip():
  6.             elem.text = indent + "  "
  7.         if not elem.tail or not elem.tail.strip():
  8.             elem.tail = indent
  9.         for elem in elem:
  10.             apply_indent(elem, level+1)
  11.         if not elem.tail or not elem.tail.strip():
  12.             elem.tail = indent
  13.     else:
  14.         if level and (not elem.tail or not elem.tail.strip()):
  15.             elem.tail = indent

Dreamy의 코드 스크랩

내가 모으고 내가 보는

List of Articles
번호 분류 제목 날짜 조회 수 추천 수
35 Python Image 기반 Steganography 예제 1 2019.07.17 25138 0
34 Python 디렉토리 없으면 만들기 2019.03.30 5650 0
33 Python 줄 바꿈 없이 출력하는 방법 2019.03.30 6728 0
32 Python Google Colab에서 파일 업로드/다운로드 팁 2019.03.06 36363 0
31 Python pandas, matplot 자주사용하는 코드 2019.03.06 4848 0
30 Python matplot에서 한글이 보이도록 하는 코드 2019.03.06 5973 0
29 Python [tensorflow] 텐서플로우 문서 한글번역본 2018.03.22 5097 0
28 Python [tensorflow] 선형회귀 예제 2018.02.05 5335 0
27 Python json 데이터 핸들링 2017.03.09 8581 0
26 Python pygoogle 파이썬으로 구글 검색결과 가져오기 library 2016.01.20 9826 0
25 Python pyBest 소스 secret 2016.01.20 0 0
24 Python 커맨드 라인에서 컬러로 출력하기 termcolor 2014.06.27 10577 0
23 Python [Sconscript] Install method 2014.05.29 8490 0
22 Python C, Python and swig on Windows with Visual Studio 2014.05.29 11502 0
» Python Python 유용한 코드 모음 2014.05.20 15102 0
목록
Board Pagination ‹ Prev 1 2 3 Next ›
/ 3

나눔글꼴 설치 안내


이 PC에는 나눔글꼴이 설치되어 있지 않습니다.

이 사이트를 나눔글꼴로 보기 위해서는
나눔글꼴을 설치해야 합니다.

설치 취소

Designed by sketchbooks.co.kr / sketchbook5 board skin

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5

Sketchbook5, 스케치북5