爱上python(几个小例子)
1、任务:简单测试局域网中的网络是否连接,ip范围:192.168.2.101到192.168.2.200。
python 实现代码:
import subprocess
cmd="cmd.exe"
begin=101
end=200
while begin<end:
p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stdin=subprocess.PIPE,stderr=subprocess.PIPE)
p.stdin.write("ping 192.168.2."+str(begin)+"\n")
p.stdin.close()
p.wait()
print "excution result:\n"
print "%s\n"%p.stdout.read()
begin=begin+1
import subprocess 是引进subprocess包,其作用主要是执行外部的命令和程序;
child.stdin,child.stdout,child.stderr分别是标准输入流,标准输出流,标准错误流;
在输入流中输入ping ip 回车即是在dos命令符下查看两个计算机之间是否有网络连接的操作,利用stdin.write()实现;
p.stdin.close()关闭输入流,p.wait()等待子进程p进行完;
print出运行结果,即p.stdout.read();%在python中有格式化输出的作用,比如:a = 'test' print 'it is a %s' %(a) 打印结果 it is a test
begin+1循环。
简单有效的python就实现了该任务。
2、删除某个文件夹(删除没有子文件夹的文件,就相当于树的叶子结点)
# -*- coding: utf-8 -*-
import os
ipath='C:\\Users\\hzj\\Desktop\\haha'
filepath=unicode(ipath,'utf8')
os.remove(filepath)
代码很简单,但是删除的时候遇到含中文路径的文件夹就出错,后来加了# -*- coding: utf-8 -*-,即把文件编码类型改为UTF-8的类型,输入这个代码就可以让.py源文件里面有中文了,用unicode()转换一下就好用了,不过这种方法不能删除空的文件夹,下面的方法可以把一个文件夹及其包含的所有子文件夹删除:(删除一个文件,包含子文件的,相当于树的根)
# -*- coding: utf-8 -*-
import shutil
ipath=('c:\\Users\\hzj\\Desktop\\删除file')
filepath=unicode(ipath,'utf8')
shutil.rmtree(filepath)
用shutil.rmtree()方法就能全部删除。而且,用python删除的文件都不会进入回收站。
清空某个文件夹:(最后只剩下一个空文件夹,树的根)
# -*- coding: utf-8 -*-
import os
ipath="c:\\Users\\hzj\\Desktop\\emptyFile"
filepath=unicode(ipath,'utf8')
for root,dirnames,filenames in os.walk(filepath,topdown=False):
for name in filenames:
os.remove(os.path.join(root,name))
for name in dirnames:
os.rmdir(os.path.join(root,name))
os.walk()函数可以得到三个参数,路径、路径下的文件夹(有子文件的)、路径下的文件,这样循环递归就可以把一个文件清空了,注意os.rmdir()函数只能删除空的文件夹,所以os.walk()函数里面的参数topdown设为False,即由下到上顺序删除文件。先删除子文件,再删除空文件夹。最后只剩下空的主文件夹。
3、修改文件名称:
# -*- coding: utf-8 -*-
import os,sys
path="c:\\Users\\hzj\\Desktop\\file"
newName=unicode('楠楠.txt','utf8')
ipath=unicode(path,'utf8')
files=os.listdir(ipath)
if 'nannan.txt' in files:
os.rename(os.path.join(ipath,'nannan.txt'),os.path.join(ipath,newName))
1、如果path指定的文件夹不是这个程序所在的目录,rename函数里面的路径就必须是绝对路径,否则就会报“WindowsError: [Error 2]”错误;
2、os.listdir()函数获取当前文件夹下面的子文件夹名称列表。
4、修改文件后缀:
# -*- coding: utf-8 -*-
import os,sys
path="c:\\Users\\hzj\\Desktop\\file"
ipath=unicode(path,'utf8')
files=os.listdir(ipath)
for name in files:
pos=name.find(".")
if pos>=0:
if name[pos+1:]=="html":
os.rename(os.path.join(ipath,name),os.path.join(ipath,name[:pos+1]+"txt"))
pos=name.find("."),就是找到字符串name中的"."的位置,比如nannan.txt,pos就是6,和数组一样,下表从0开始,这样name[pos+1:]就是name[7:],就是"txt",name[:pos+1]就是"nannan.",name[1:5]就是"anna",其它同理。
find()函数如果找不到指定的字符串的话就会返回 ‘-1' 。
还有一种方式可以同时实现上面的功能,代码如下:
# -*- coding: utf-8 -*-
import os,sys
path="c:\\Users\\hzj\\Desktop\\file"
ipath=unicode(path,'utf8')
files=os.listdir(ipath)
for name in files:
li=os.path.splitext(name)
if li[1]==".txt":
os.rename(os.path.join(ipath,name),os.path.join(ipath,li[0]+".html"))
用到了os.path.splitext()函数,它可以把一个文件名分割成两部分,比如nannan.txt,分割后得到li,li[0]="nannan",li[1]=".txt",所以得到该方法。
未完待续。。。
爱上python(几个小例子)的更多相关文章
- Python,while循环小例子--猜拳游戏(三局二胜)
Python,while循环小例子--猜拳游戏(三局二胜) import random all_choice = ['石头', '剪刀', '布'] prompt = '''(0)石头 (1)剪刀 ( ...
- python 字典 get 小例子
语法 get()方法语法: dict.get(key, default=None) 参数 key -- 字典中要查找的键. default -- 如果指定键的值不存在时,返回该默认值值. 返回值 返回 ...
- python,栈的小例子
''' 1.首先确认栈的概念,先进后出 2.初始化的时候如果给了一个数组那么就要将数组进栈 ''' class Stack: def __init__(self,start=[]): self.sta ...
- [Spark][Python]Spark Join 小例子
[training@localhost ~]$ hdfs dfs -cat people.json {"name":"Alice","pcode&qu ...
- python事件驱动的小例子
首先我们写一个超级简单的web框架 event_list = [] #这个event_list中会存放所有要执行的类 def run(): for event in event_list: obj = ...
- 由Python的一个小例子想到的
习题: L = [1,2] L.append(L) Print L 问,结果是什么. 结果是,[1,2,[...]] 这是什么意思呢?就是说[...]表示的对[1,2]的无限循环.这一点是在C#等静态 ...
- python 基础 字典 小例子
统计单词次数 作为字典存储 cotent = "who have an apple apple is free free is money you know" result = { ...
- python 基础 列表 小例子
存主机ip到列表 host_list=[] netip='192.168.1' for hostip in range(1,254): ip = netip +str(hostip) host_lis ...
- Python,for循环小例子--99乘法表
一.99乘法表 for i in range(1, 10): for j in range(1, i + 1): print('%sx%s=%s ' % (j, i, j * i), end='') ...
- [Spark][Hive][Python][SQL]Spark 读取Hive表的小例子
[Spark][Hive][Python][SQL]Spark 读取Hive表的小例子$ cat customers.txt 1 Ali us 2 Bsb ca 3 Carls mx $ hive h ...
随机推荐
- 项目笔记《DeepLung:Deep 3D Dual Path Nets for Automated Pulmonary Nodule Detection and Classification》(二)(上)模型设计
我只讲讲检测部分的模型,后面两样性分类的试验我没有做,这篇论文采用了很多肺结节检测论文都采用的u-net结构,准确地说是具有DPN结构的3D版本的u-net,直接上图. DPN是颜水成老师团队的成果, ...
- 转——.ashx文件与.ashx.cs
作者:PBDragon 原文连接:http://www.cnblogs.com/PBDragon/p/3811831.html 如果项目是“新建网站”,添加的ashx是没有ashx.cs的:如果是新建 ...
- linux安装php7
之前一直对linux研究的比较少,终于下定决心好好把linux玩一下 首先~我是安装了vm虚拟机,然后使用的是centos7的版本.因为vm不好复制粘贴,故使用了xshell连接了我的linux进行操 ...
- UBoot添加命令的方法
1. 具体实现步骤 ① 在./common文件夹下新建cmd_led.c,并在此文件中添加如下内容 #include <common.h> #include <command.h&g ...
- canvas基础入门(一)canvas的width、height于css样式中的宽高区别
canvas的width.height于css样式中的宽高对画布的内容显示是有所区别的 1.在canvas标签下调用他的width和height,而且是没有单位的宽高,这种指定canvas大小的方法也 ...
- 第五章:引用类型(一)-Object和Array
引用类型 引用类型的值(对象)是引用类型的一个实例 引用类型是一种数据结构,用于将数据与功能组织在一起 也常被称为类, Object 对象的两种创建方式 使用new操作符 对象字面量表示法 Array ...
- 转 OGG-01224 TCP/IP error 111 (Connection refused); retries exceeded.
https://blog.csdn.net/yabingshi_tech/article/details/40620351 在源端启动goldengate pump进程,状态起初是running,后来 ...
- 干货-Spring3.2.3的所有注解
在用到Spring3的时候,我们需要对耦合的struts2的Action层或者SpringMVC的Controller层加上注解,一般是@Controller和@RequestMapping 看到这里 ...
- SQL Server Reporting Service(SSRS) 第六篇 SSRS 部署总结
前段时间完成了第一批次SSRS报表的开发,本来以为大功已经告成,结果没有想到在整个发布与部署过程中还是遇到了很多的问题,现将这些问题一一列举出来,希望对以后能够有所启发! 1. 关于数据源与数据集的发 ...
- tomcat异常[0]--java.lang.ClassNotFoundException: org.apache.taglibs.standard.tlv.JstlCoreTLV
自己建了一个项目,启动项目的时候,发生了java.lang.ClassNotFoundException: org.apache.taglibs.standard.tlv.JstlCoreTLV异常. ...