文章目录
常用语句
1 记录脚本命令的自定义函数
把每次脚本执行的命令和参数记保存到一个文件里,以便以后查看
import sys,time
def command_log_record(cmd):
""" This is to record the command lint to a log file
"""
cmd_log = 'Issued' # the log file name
cmd_file=open(cmd_log,'a+')
localtime = time.asctime( time.localtime(time.time()))
cmd_file.write('---- Time : ')
cmd_file.wirte(localtime)
cmd_file.wirte('\n')
cmd_file.wirte('python ')
for i in cmd:
cmd_file.wirte('i')
cmd_file.wirte(' ')
cmd_file.wirte('\n')
cmd_file.close()
#使用时放到main的最前头
def main(argv):
""" main function """
dir_path = os.getcmd()
cmommand_log_record(sys.argv[0:])
...
if __name__ == '__main__'
main(sys.argv[1:])
2 字符串处理函数
2.1 字符串分割 split()
str = "Num1-abcmm \nNum2-abc \nNum3-abcnn";
print str.split( ); # 以空格为分隔符,包含 \n
print str.split(' ', 1 ); # 以空格为分隔符,分隔成两个
'''
输出结果:
['Num1-abcmm', '\nNum2-abc', '\nNum3-abcn']
['Num1-abcmm', '\nNum2-abc \nNum3-abcn']
2.2 删除首尾特定字符 strip()
strip() 移除字符串头尾制定的字符或字符序列,默认为空格或换行符。该函数不能删除中间部分
#str.strip([chars])
str1="e my best life"
print str1.strip('e') # delete 首尾 'e'
str2=" Hello world "
print str2.strip( ) # 删除首尾' '
3 脚本中执行系统命令
import os
os.system("cp -rf fold_a fold_b")
4 range() 列表产生函数
range() 函数可创建一个整数列表,一般用在 for 循环中。
函数语法
range(start, stop[, step])
参数说明:
- start: 计数从 start 开始。默认是从 0 开始。例如range(5)等价于range(0, 5);
- stop: 计数到 stop 结束,但不包括 stop。例如:range(0, 5) 是[0, 1, 2, 3, 4]没有5
- step:步长,默认为1。例如:range(0, 5) 等价于 range(0, 5, 1)
实例
>>>range(10) # 从 0 开始到 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11) # 从 1 开始到 11
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5) # 步长为 5
[0, 5, 10, 15, 20, 25]
>>> range(0, 10, 3) # 步长为 3
[0, 3, 6, 9]
>>> range(0, -10, -1) # 负数
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> range(0)
[]
>>> range(1, 0)
[]
#以下是 range 在 for 中的使用,循环出runoob 的每个字母:
>>>x = 'runoob'
>>> for i in range(len(x)) :
... print(x[i])
5 文件操作
input = open('filename','r') # 打开文件,只读
input = open('filename') # 打开文件,只读
output = open('filename','w') # 打开文件,可写
output.close() #关掉
aStr = input.readline() #读取文件的一行
aStr = input.read() #读取整个文件到一个string里
aStr = input.read(N) #读取文件的N个char到一个string里
aList = input.readlines() #读取整个文件到行内容字符串列表里
input.seek(N) #change file position to offset N for next operation
for line in open('data_file') : use line # 一行行的读取文件内容
本博客所有文章均同步发表于www.mx1980.cn/blog