선 밖에 선 자유인

간단한 파이썬 스크립트들 본문

IT/Programming

간단한 파이썬 스크립트들

Hotman 2012. 1. 17. 13:13
1. 파일명을 인자로 전달하여 해당 파일에 있는 tab 문자 4개를 스페이스로 변경한다.
#tabto4.py

import re
import sys

def usage():
    print "Usage: python %s filename" % sys.argv[0]

try: f = open(sys.argv[1])
except: usage(); sys.exit(2)

msg = f.read()
f.close()
p = re.compile(r'\t')
changed = p.sub(" "*4, msg)

f = open(sys.argv[1], 'w')
f.write(changed)
f.close()
2. 간단한 메모장
#-*-coding:cp949-*-
# memo.py

import sys
import time

def usage():
	print """
	
Usage
=====================
python %s -v : View memo
python %s -a : Add memo
""" % (s7s.argv[0], sys.argv[0])

if not sys.argv[1:] or sys.argv[1] not in ['-v', '-a']:
	usage()
	
elif sys.argv[1] == '-v':
	try:
		print open("memo.txt").read()
	except IOError:
		print "memo does not exist!"
	
elif sys.argv[1] == '-a':
	word = raw_input("Enter memo : ")
	f = open("memo.txt", 'a')
	f.write(time.ctime() + ': ' + word+'\n')
	f.close()
	print "Added"

3. 12345라는 숫자를 12,345처럼 바꾸기
# commanumber.py
#-*-coding: cp949-*-

import string

def comma_number(number):
	if number[0] in ['+', '-']:
		sign_mark, number = number[:1], number[1:]
	else:
		sign_mark = ''




	try:
		tmp = string.split(number, '.')
		num = tmp[0]
		decimal = '.' + tmp[1]
	except:
		num = number; decimal = ''
	
	head_num = len(num) % 3
	result = ''
	for pos in range(len(num)):
		if pos == head_num and head_num:
			result = result + ','
		elif (pos - header_num) % 3 == 0 and pos:
			result = result + ','
		result = result + num[pos]
	return sign_mark + result + decimal
	
print comma_number("12345678.345678")


4. 하위디렉토리 검색
#-*-coding:cp949-*-
# search directory

import os

def search(dirname):
	flist = os.listdir(dirname)
	for i in flist;
		next = os.path.join(dirname, f)
		if os.path.isdir(next):
			search(next)
		else:
			doFileWork(next)
			
			
def doFileWork(filename):
	ext = os.path.splitext(filename)[-1]
	if ext == '.py':
		print filename
		

search("d:\")
출처 : 점프 투 파이썬 http://wikidocs.net/read/689
Comments