Chinaunix首页 | 论坛 | 博客
  • 博客访问: 4471626
  • 博文数量: 1214
  • 博客积分: 13195
  • 博客等级: 上将
  • 技术积分: 9105
  • 用 户 组: 普通用户
  • 注册时间: 2007-01-19 14:41
个人简介

C++,python,热爱算法和机器学习

文章分类

全部博文(1214)

文章存档

2021年(13)

2020年(49)

2019年(14)

2018年(27)

2017年(69)

2016年(100)

2015年(106)

2014年(240)

2013年(5)

2012年(193)

2011年(155)

2010年(93)

2009年(62)

2008年(51)

2007年(37)

分类: Python/Ruby

2010-05-06 19:08:25

1.python的几个基本的函数

#输出'str'并读输入的字符串到s
s = raw_input('str')

#把字符串s强制转换为int型,类似atoi
int(s)

#字符串s的长度
len(s)

#for循环中数字递减
range(5,2,-1)

2.函数返回值
没有返回值的return语句等价于return None。None是Python中表示没有任何东西的特殊类型。例如,如果一个变量的值为None,可以表示它没有值。除非你提供你自己的return语句,每个函数都在结尾暗含有return None语句。

def someFunction():
pass
pass语句在Python中表示一个空的语句块。

import os
删除文件: 
os.remove()
删除空目录: 
os.rmdir()
递归删除空目录: 
os.removedirs()
递归删除目录和文件(类似DOS命令DeleteTree): 
方法1:自力更生,艰苦创业
# Delete everything reachable from the directory named in 'top',
# assuming there are no symbolic links.
# CAUTION:  This is dangerous!  For example, if top == '/', it
# could delete all your disk files.
import os
for root, dirs, files in os.walk(top, topdown=False):
    for name in files:
        os.remove(os.path.join(root, name))
    for name in dirs:
        os.rmdir(os.path.join(root, name))
方法2:前人栽树,后人乘凉 
import shutil 
shutil.rmtree()
一行搞定 __import__('shutil').rmtree()

4.对字符串IP和HBOip之间的转换:
socket.ntohl(struct.unpack('I', socket.inet_aton('192.168.0.1'))[0])
socket.inet_ntoa(struct.pack('I', socket.htonl(2035413478)))

注:
a.如果python<=2.4,结果HBOip地址为128.0.0.0及其以上时,会为负数,需要正数得再次的pack,unpack
struct.unpack('I', struct.pack('I', socket.ntohl(struct.unpack('I', socket.inet_aton('192.168.0.1'))[0])))[0]
b.如果python>=2.5,结果HBOip地址为128.0.0.0及其以上时,会为正数,如果需要负数,必须再次的pack,unpack
struct.unpack('i', struct.pack('I', socket.ntohl(struct.unpack('I', socket.inet_aton('192.168.0.1'))[0])))[0]

5.把文件读到内存,修改内存之后,把内存数据写入文件:

fd = open("socketip", "r+")
lines = fd.readlines()
ip = socket.ntohl(struct.unpack('I', socket.inet_aton(lines[0][:-1]))[0])
lines[0] = str(ip) + '\n'
fd.truncate(0) # 截0后文件确实变0byte了
fd.seek(0, 0) # 但还是要seek,不然写入的文件开头有一堆奇怪的非ASCII字符
fd.writelines(lines)
fd.close()


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