Chinaunix首页 | 论坛 | 博客
  • 博客访问: 271436
  • 博文数量: 55
  • 博客积分: 2030
  • 博客等级: 大尉
  • 技术积分: 737
  • 用 户 组: 普通用户
  • 注册时间: 2006-04-13 18:06
文章分类

全部博文(55)

文章存档

2011年(2)

2010年(7)

2009年(17)

2008年(29)

我的朋友

分类: Python/Ruby

2009-10-22 10:27:54

文件查找:fnmatch
参数处理:getopt, optparse
数据图绘制:matplotlib
科学计算:numpy, scipy
正则表达式:re

#!/usr/bin/python
import sys, os

# this statement
line = sys.stdin.readline()
# is equivalent to
line = raw_input()
# is equivalent to
for line in sys.stdin:
    pass

# check argument number
if len(sys.argv) == 1:
    pass

# if stdin is console
if sys.stdin.isatty():
    pass

# check platform
if sys.platform[:3] == 'win':
    import msvcrt
    msvcrt.putch('?')
    key = msvcrt.getche()
    pass
elif sys.platform[:5] == 'linux':
    pass

# find in string
self = '\n'
eoln = self.text.find('\n')
if eoln == -1:
    pass
else:
    pass

# print in stderr
sys.stderr.write('error!')
print >> sys.stderr, 'error!'

# split string
output = 'hello\nworld\n'
for line in output.split('\n'):
    print line


# file redirection
dbfile = open('input.txt')    # recommended
sys.stdin = dbfile

fdfile = sys.stdout.fileno
objfile = os.fdopen(fdfile)

# cyclic input
while True:
    try:
        line = raw_input()
    except EOFError:
        break
    else:
        pass

# file process

file = open('data.txt', 'r')
for line in file:
    print line,

for line in open('data.txt', 'r'):
    print line,

for line in file.readlines():
    print line,

# strip the trailing \n
lines = [line.rstrip() for line in open('data.txt')]

# import module
import sys
sys.path.append("..")

# or create __init__ in directory

# print
print('hello'),    # not start a newline
sys.stdout.write('hello')
os.write(1, 'hello')

# retrieve file's meta infomation
info = os.stat(r'
data.txt')
import stat
print(info[stat.ST_MODE], info[stat.ST_SIZE])

path = r'
data.txt'        # recommended
os.path.isdir(path), os.path.isfile(path), os.path.getsize(path)

# scan file
while True:
    line = file.readline()
    if not line:
        break
    else:
        print(line[:-1])

# define customized exception
class UnknownCommand(Exception):
    pass
try:
    pass
except KeyError:
    raise UnknownCommand

# function iterator
map(str.rstrip, open('
data.txt', 'r'))

[str.rstrip(line) for line in open('
data.txt', 'r')]

# get output of command
for line in os.popen('
ls').readlines():
    print(line[:-1])

import glob
glob.glob('
*')    # recommanded, implicitly fnmatch

os.listdir('
.')    # more recommanded

# process pathname and basename
for file in glob.glob('
*'):
    head, tail = os.path.split(file)

for file in os.listdir('
.'):
    print os.path.join('
.', file)

# recursively visit
def lister(dummy, dirname, fileindir):
    exceptions = ('
.', '..')
    if fileindir not in exceptions:
        print fileindir

os.path.walk('
.', lister, None)

os.walk

#exception example
try:
    names = os.listdir('
.


阅读(1192) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~