python常用方法_Python常用方法

copycode.gif

ips ={}

with open("/root/access.log-20180629") as fh:

for line infh:

ip = line.split(" ")[0]

if 6 < len(ip) <=15:

ips[ip] = ips.get(ip, 0) + 1ip_num =[]

for ipaddr,num inips.items():

ip_num.append((ipaddr,num))

ip_num.sort(key=lambda x: x[1], reverse=True)

for ipaddr,num in ip_num[:20]:

print('IP地址为{}, 访问次数为{}'.format(ipaddr,num))

copycode.gif

压缩和解压文件

# 压缩tar.gz

import os

import tarfiletar = tarfile.open("/root/test/test.tar.gz","w:gz") # 创建压缩包名for path,dir,files in os.walk("/root/test"): # 递归文件目录for file infiles:

fullpath= os.path.join(path,file)tar.add(fullpath) # 创建压缩包tar.close()

#解压tar.gz

importtarfile

tar= tarfile.open("/root/test/test.tar.gz")#tar.extract("/tmp") # 全部解压到指定路径

names = tar.getnames() #包内文件名

for name innames:

tar.extract(name,path="./") #解压指定文件

tar.close()

gzip [解压缩gzip 删除原文件]#压缩gzip

importgzip

f_in= open('file.log', 'rb')

f_out= gzip.open('file.log.gz', 'wb')

f_out.writelines(f_in)

f_out.close()

f_in.close()#压缩gzip

File= 'xuesong_18.log'g= gzip.GzipFile(filename="", mode='wb', compresslevel=9, fileobj=open((r'%s.gz' %File),'wb'))

g.write(open(r'%s' %File).read())

g.close()#解压gzip

g= gzip.GzipFile(mode='rb', fileobj=open((r'xuesong_18.log.gz'),'rb'))

open((r'xuesong_18.log'),'wb').write(g.read())

输入参数判断

try:

textfile1=sys.argv[1]

textfile2=sys.argv[2]exceptException,e:print "Error:"+str(e)print "Usage: simple3.py filename1 filename2"sys.exit()

判断输入参数是否为2个

if len(sys.argv) > 2:

dir1=sys.argv[1]

dir2=sys.argv[2]else:print "Usage:", sys.argv[0], "datadir backupdir"sys.exit()

输入去掉空白

_input = input('please input your opinion:')

ret= _input.strip()

Python执行linux命令并得到执行结果

subprocess

#!/usr/bin/env python#coding: utf-8

importsubprocessdefcreate_process(cmd):

p= subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

result=p.stdout.read()

code=p.wait()returncode, result

code,result= create_process('ls -l test.py')#print(code)#print(result)#根据返回码判断是否执行成功

ifcode:print("备份MySQL失败")print(code, result)else:print("备份MySQL成功")print(code, result)

利用执行命令后的返回代码判断

利用执行命令后的返回代码判断#coding:utf-8

importosimportsubprocess

cmd= 'ls -l test.txt'retcode= subprocess.call(cmd, shell=True)

result=p.returncodeif retcode !=0:print("备份MySQL失败")#print(ret)

else:print("备份MySQL成功")

commands

#!/usr/bin/env python#coding: utf-8

importsysimportosimportcommands

status,output=commands.getstatusoutput('ls -l test.py')if(status!=0):print "command is failed, please check"

printoutput

sys.exit(1)else:print "command is sucess."

os.system

os.system('ls -l /root')

ftp客户端ftplib

from ftplib importFTP

ftp = FTP('10.112.13.98') #连接ftp地址 FTP(host,port,timeout)

ftp.login(test1,f0W1V7kw) #使用默认anonymous登录 login(user,passwd)

ftp.cwd('debian') #切换到目录debian

ftp.retrlines('LIST') #打印目录列表

ftp.retrbinary('RETR README', open('README', 'wb').write) #下载文件写到本地

ftp.storbinary("STOR "+filename, fp, bufsize) # 上传目标文件

ftp.delete('filename') #删除ftp中文件

ftp.mkd('dirname') #在ftp上创建目录

ftp.size('filename') #查看文件大小

ftp.quit()

示例

#!/usr/bin/env python#coding: utf-8

importtimeimportosimportftplibfrom ftplib importFTP

user='username'password='password'filename= 'u_ex'+ time.strftime('%y%m%d') + '.log'

for root,dirs,files in os.walk(r"C:\inetpub\logs\LogFiles\W3SVC2"):for file infiles:#获取文件所属目录

#print(root)

#获取文件路径

#print(os.path.join(root,file))

if filename inos.path.join(root,file):print(os.path.join(root,file))

local_file=os.path.join(root,file)#print(type(local_file))

bufsize= 1024fp= open(local_file, 'rb')

ftp= FTP('IP') #连接ftp地址 FTP(host,port,timeout)

ftp.login(user, password) #使用默认anonymous登录 login(user,passwd)

ftp.cwd('debian') #切换到目录debian

ftp.storbinary("STOR"+filename, fp, bufsize) #上传目标文件

ftp.retrlines('LIST') #打印目录列表

ftp.quit()

fp.close()print('upload file success.')

python按行读取文件,如何去掉换行符"\n"

for line infile.readlines():

line=line.strip('\n')

1、列表与字符串转换

列表转字符串:

将列表中的内容拼接成一个字符串

1261262-20180713161535987-991749041.png

将列表中的值转成字符串

1261262-20180713162259107-1782465935.png

字符串转列表:

用eval转换

1261262-20180716105326641-63314715.png

将字符串每个字符转成列表中的值

1261262-20180713162656213-1653686962.png

将字符串按分割成列表

1261262-20180713185937378-642261143.png

2、列表与字典转换

列表转字典:

将两个列表转成字典

1261262-20180713191339747-780451434.png

将嵌套列表转为字典

1261262-20180713192006506-806531958.png

字典转列表:

字典中键、值转为列表

1261262-20180713193130205-1291529611.png

3、字典与字符串转换

字符串转字典:

用eval转换

1261262-20180716105628148-1328276570.png

用json.loads 转换

1261262-20180716111324617-1774020375.png

字典转字符串:

用json.dumps 转换

1261262-20180716111629419-1182078233.png

强转换

1261262-20180716112148700-1270125411.png

列表转换成字典

def GenPassword_reg(length=16, chars=string.ascii_letters +string.digits):return ''.join([choice(chars) for i inrange(length)])

dic={}#result 是个列表

for i inresult:

dic[i]=GenPassword_reg()print(dic)

shell与python间传递变量方法

python -> shell:

1.环境变量importos

var=123或var=’123’

os.environ[’var’]=str(var) #environ的键值必须是字符串

os.system(’echo $var’)2.字符串连接importos

path=’/root/a.txt’

var=[1]

var=’bash’

os.system(’echo ’+ path) #注意echo后有空格

os.system(‘echo ‘ +str(var[0]))

os.system(’echo ’+ var + ’ /root/c.sh’) #注意echo后和/root前有空格

3.通过管道importos

var=’123’

os.popen(’wc-c’, ’w’).write(var)4.通过文件

output= open(‘/tmp/mytxt’, ‘w’)

output.write(S)#把字符串S写入文件

output.writelines(L) #将列表L中所有的行字符串写到文件中

output.close()5.通过重定向标准备输出

buf= open(’/root/a.txt’, ’w’)print >> buf, ‘123\n’, ‘abc’

或print >> open(‘/root/a.txt’, ‘w’), ‘123\n’, ‘abc’ #写入或生成文件

print >> open(‘/root/a.txt’, ‘a’), ‘123\n’, ‘abc’ #追加

shell -> python:

1.管道importos

var=os.popen(’echo -n 123’).read( )printvar2.importcommands

var=commands.getoutput(’echo abc’) #输出结果

var=commands.getstatusoutput(’echo abc’) #退出状态和输出结果

3.文件

input= open(‘/tmp/mytxt’, ‘r’)

S= input.read( ) #把整个文件读到一个字符串中

S = input.readline( ) #读下一行(越过行结束标志)

L = input.readlines( ) #读取整个文件到一个行字符串的列表中

转自:原文链接:https://blog.csdn.net/kpshare/article/details/7523511

python用变量拼接成 shell命令执行

def create_process(cmd):

p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)

result = p.stdout.read()

code = p.wait()

return code, result

mysql_trunc = '/usr/local/mysql/bin/mysql -uroot -p -h localhost -N -e "select * from moffice_hnair_schedule_log_his.' + str(final_list[-1]) + 'limit 1"'

print(mysql_trunc)

code, result=create_process(mysql_trunc)if code !=0:print("执行MySQL清除log_interface_result失败")print(result)else:print("执行MySQL清除log_interface_result成功")print(result)

在windows下删除文件报错

715460-20191126161025107-1864017143.png

WindowsError: [Error 123] : 'C:\\Users\\chh-huang\\Desktop\test\\2019-11-23.txt'

filename = r'C:\Users\chh-huang\Desktop\test\\' + name

需要在路径前加r,这样就没问题了

filename = r'C:\Users\chh-huang\Desktop\test' + os.sep +name

等于

filename= r'C:\Users\chh-huang\Desktop\test\\' + name

其中,os.sep根据你所处的平台,自动采用相应的分隔符号

>>> os.sep

'/'

Python删除过期文件

#-*- coding:utf8 -*-#!/usr/bin/python

importosimportdatetimeimporttimeimportshutilfor root, dirs, files in os.walk(r'C:\Users\chh-huang\Desktop\test'):for name infiles:

(y1, m1, d1)= (int(x) for x in name.split('.')[0].split('-'))#print(y1, m1, d1)

date1 =datetime.date(y1, m1, d1)

datenow= time.strftime('%Y%m%d')

y2= int(datenow[:4])

m2= int(datenow[4:6])

d2= int(datenow[6:])

date2=datetime.date(y2, m2, d2)#print(date1, date2)

# 删除大于等于2天的文件

if (date2 - date1).days >= 2:print 'Expired file! Deleting file...', nameprint('os.remove(%s)' %name)#filename = r'C:\Users\chh-huang\Desktop\test\\' + name

filename = r'C:\Users\chh-huang\Desktop\test' + os.sep +name

os.remove(filename)

import os

importtimeimport datetime

import shutil

filepath= r"xxx"timestamp=os.path.getctime(filepath) # 获取文件创建的时间戳

timestruct= time.localtime(timestamp) # 将时间戳转换成本地时间

file_create_time= time.strftime('%Y-%m-%d', timestruct) # 本地时间转换成字符串

current_time= time.strftime('%Y-%m-%d') # 获取当前时间

# 利用datetime来计算时间差

day1= datetime.datetime.strptime(file_create_time, '%Y-%m-%d')

day2= datetime.datetime.strptime(current_time, '%Y-%m-%d')

delta= day2 -day1

print(delta.days) # 获取当前时间与文档创建时间之差if delta.days>3: # 删除创建日期大于3天的文件

shutil.rmtree(filepath)

参考

(3条消息)python 根据时间间隔删除文件夹内修改时间比较早的文件_weixin_38383877的博客-CSDN博客 https://blog.csdn.net/weixin_38383877/article/details/82897359

Python实现删除文件夹内规定时间内的文件 - 爱我所艾 - 博客园 https://www.cnblogs.com/wangchy0927/archive/2013/08/30/3291304.html

(3条消息)python 删除指定时间间隔之前的文件_百恼专栏-CSDN博客 https://blog.csdn.net/zsy19881226/article/details/72638036

Python实现删除文件夹内规定时间内的文件 - 爱我所艾 - 博客园 https://www.cnblogs.com/wangchy0927/archive/2013/08/30/3291304.html

使用Python批量删除文件前缀的操作方法-百度经验 https://jingyan.baidu.com/article/1974b289eaab0eb4b0f7746a.html

清理以开头过期日志文件

#!/usr/bin/envpython

# coding: utf-8import os

import shutil

import datetime

importtimesrc_dir= r'C:\Windows\System32\LogFiles\Sum'dst_dir= r'G:\log-svcbak'

for file inos.listdir(src_dir):

# 找出以svc开头的log文件if file[:3] == 'Svc' and file[-3:] == 'log':

# 排除Svctmp.log或Svc.log文件if file == 'Svctmp.log' or file == 'Svc.log':

continue

# print('%s was been moved' % file)

src_file= src_dir + '\\' + file# os.remove(src_file)

# print(src_file)

timestamp=os.path.getmtime(src_file)

timestruct= time.localtime(timestamp)

file_create_time= time.strftime('%Y-%m-%d', timestruct)

current_time= time.strftime('%Y-%m-%d')

day1= datetime.datetime.strptime(file_create_time, '%Y-%m-%d')

day2= datetime.datetime.strptime(current_time, '%Y-%m-%d')

delta= day2 -day1

# print(file_create_time, current_time, day1, day2, delta.days, src_file)

# 删除大于21天的文件if delta.days > 21:

print(src_file)

# os.remove(src_file)

# shutil.rmtree(filepath)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值