主要记录初学者常用的一些代码:

1.获取当前时间
# -*- coding: gbk -*-
import os
import time
import shutil

today = time.strftime('%Y-%m-%d 星期%w')
now = time.strftime('%H:%M:%S')
>>>
2008-05-07 星期3
20:28:14

2.os.path常见属性
os.path.sep :路径分隔符 。以前老爱用'\\'  ,后来用'/'。
os.path.altsep:(根目录,不是很确定,我用来做根目录。反正在windows表现是'/')
os.path.curdir: 当前目录
os.path.pardir: 父目录

3.判断是否是指定文件类型
File.rsplit('.',1)[-1] == type
当然也可以写成File.split('.')[-1:][0] == type




posted on 2008-05-07 20:44 -274°C 阅读(15379) 评论(15)  编辑  收藏 所属分类: python


FeedBack:
# re: python代码总结
2008-05-07 21:20 | -274°C
4.中文字符

>>> aa = "a是中国人"
>>> print aa
a是中国人
>>> print aa[1]
Ê
>>> print aa[1:3]

>>> c = unicode(aa,"gb2312")
>>> print c[1]

>>> print len(c)
5
>>> print len(aa)
9  回复  更多评论
  
# re: python代码总结
2008-05-07 21:30 | -274°C
5.python中对字符串排序:
>>> s = "string"
>>> l = list(s)
>>> l.sort()
>>> s = "".join(l)
>>> s
'ginrst'
  回复  更多评论
  
# re: python代码总结
2008-05-07 22:45 | -274°C
6.BASE64对字符串编码和解码

a= "this is a teat"
b = base64.encodestring(a)
print b
>>>
dGhpcyBpcyBhIHRlYXQ=
print base64.decodestring(b)
>>>this is a teat

  回复  更多评论
  
# re: python代码总结
2008-05-10 19:56 | java_he
7.获取当前路径
os.getcwd()
改变当前路径
os.chdir(r"c:/")  回复  更多评论
  
# re: python代码总结
2008-05-10 22:53 | java_he
8.修改文件名称
os.rename("bbb.txt","ccc.txt")
如果ccc.txt已经存在,则有异常抛出

  回复  更多评论
  
# re: python代码总结
2008-05-10 22:56 | java_he
8.文件夹改名
os.rename("aaa","ccc")
如果ccc已经存在,则有异常抛出   回复  更多评论
  
# re: python代码总结
2008-05-19 15:23 | java_he

1.打印出xml文件的内容

from xml.dom import minidom
xmldoc = minidom.parse('binary.xml')
print xmldoc
print xmldoc.toxml()

2.判断字符串以什么结尾和开头

string2.upper().startswith("EVEN")
string2.upper().endswith("EVEN")

3.比较时候以大,小写来比较,字符串本身并未发生改变
>>> print string2
Odd or even
>>> print string2.lower()
odd or even
>>> print string2.upper()
ODD OR EVEN
>>> print string2
Odd or even
>>>

4.从url解析xml

>>> import urllib
>>> usock = urllib.urlopen('http://www.blogjava.net/JAVA-HE/category/19871.html/rss')
>>> xmldoc = minidom.parse(usock)
>>> usock.close()
>>> print xmldoc.toxml()

5.把string解析为xml

>>> from xml.dom import minidom
>>> contents = "<grammar><ref id='bit'><p>0</p><p>1</p></ref></grammar>"
>>> xmldoc = minidom.parseString(contents)
>>> print xmldoc.toxml()
<?xml version="1.0" ?><grammar><ref id="bit"><p>0</p><p>1</p></ref></grammar>

以前做AJAX 用到xml,python 使用在这方面是非常简单的。至少对使用者来讲屏蔽了许多繁琐的代码。

6.python 2.5 后 ,集合

>>> b = set()
>>> b.add(1)
>>> b.add(2)
>>> b.add(3)
>>> c = set()
>>> c.add(3)
>>> c.add(4)
>>> c.add(5)
>>> d = b.difference(c)
>>> print d
set([1, 2])
>>> print c.difference(b)
set([4, 5])
>>> print c.union(b)
set([1, 2, 3, 4, 5])
>>> print b.union(c)
set([1, 2, 3, 4, 5])
>>> print b.intersection(c)
set([3])

difference求不同 union求并集 infference 交集

7.操作系统版本
>>> import os
>>> print os.name
nt
>>> import sys
>>> print sys.platform
win32
>>> print sys.getwindowsversion()
(5, 1, 2600, 2, 'Service Pack 2')
>>>

8.正则表达式获取文件列表

import glob
# 生成当前路径下所有文件的列表
a = glob.glob('*')
print a
# 生成当前路径下所有扩展名为gif的文件列表。
a = glob.glob('*.gif')

9.python 2.4 后,参数可以函数的实例
>>> def hehe(tt):
return 'hehe'+tt()

>>> def test():
return 'test'

>>> test = hehe(test)
>>> print test
hehetest

10.range和xrange
for i in range(0, 100):
print i

for i in xrange(0, 100):
print i

这两个输出的结果都是一样的,实际上有很多不同,range会直接生成一个list对象:

a = range(0,100)
print type(a)
print a
print a[0], a[1]

而xrange则不会直接生成一个list,而是每次调用返回其中的一个值

a = xrange(0,100)
print type(a)
print a
print a[0], a[1]

所以xrange做循环的性能比range好,尤其是返回很大的时候!

11.python里任何对象都可以print

用 print 打印一个对象的时候,实际上会调用这个对象的__str__函数。
所以 print 不仅仅是可以用来打印字符串和数字的。
class A:
def __init__(self):
self.a = 1

def __str__(self):
return str(self.a)

a = A()
print a

输出:
1

12.两种遍历目录对比

>>> files = os.listdir(".")
>>> for f in files:
print "." + os.sep + f

上面这种已经用过了。下面是一种递归遍历的:

for root, dirs, files in os.walk("."):
for name in files:
print os.path.join(root,name)  回复  更多评论
  
# re: python代码总结
2008-05-20 10:47 | java_he
1.对象拷贝:

import copy

a = [[1],[2],[3]]
b = copy.copy(a)

print "before", "=>"
print a
print b

# modify original
a[0][0] = 0
a[1] = None

print "after", "=>"
print a
print b

before =>
[[1], [2], [3]]
[[1], [2], [3]]
after =>
[[0], None, [3]]
[[0], [2], [3]]

  回复  更多评论
  
# re: python代码总结
2008-06-14 17:18 | -274°C
10. 获取文件CRC

from ctypes import *
import binascii

def getFileCRC(_path):
try:
blocksize = 1024 * 64
f = open(_path,"rb")
str = f.read(blocksize)
crc = 0
while(len(str) != 0):
crc = binascii.crc32(str, crc)
str = f.read(blocksize)
f.close()
except:
klog.error("get file crc error!")
return 0
return c_uint(crc).value  回复  更多评论
  
# re: python代码总结
2008-10-07 14:04 |
为何运行不了  回复  更多评论
  
# re: python代码总结
2008-10-07 21:05 | 274
@曲

代码都是运行过的。注意缩进。  回复  更多评论
  
# re: python代码总结
2008-11-12 09:51 | amanda
how to get the current wiki page's url?  回复  更多评论
  
# re: python代码总结
2008-12-12 18:16 |
不错噢,多加油!  回复  更多评论
  
# re: python代码总结
2009-08-06 18:41 | zngsai
@-274&#176;C
我的怎么是这个:
>>> aa = 'woshi中国人'
>>> aa
'woshi\xd6\xd0\xb9\xfa\xc8\xcb'  回复  更多评论
  
# re: python代码总结
2009-08-06 18:41 | zngsai
@-274&#176;C
我的怎么是这个:
>>> aa = 'woshi中国人'
>>> aa
'woshi\xd6\xd0\xb9\xfa\xc8\xcb'  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航:
 

常用链接

留言簿(21)

随笔分类(265)

随笔档案(242)

相册

JAVA网站

关注的Blog

搜索

  •  

积分与排名

  • 积分 - 909071
  • 排名 - 40

最新评论