python集腋成裘

本文深入探讨了Python编程中的实用技巧,包括自定义函数记录脚本命令、字符串处理如split()和strip()函数的使用、如何在脚本中执行系统命令、range()函数的灵活运用以及基本的文件操作方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

常用语句

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值