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(几个小例子)的更多相关文章

  1. Python,while循环小例子--猜拳游戏(三局二胜)

    Python,while循环小例子--猜拳游戏(三局二胜) import random all_choice = ['石头', '剪刀', '布'] prompt = '''(0)石头 (1)剪刀 ( ...

  2. python 字典 get 小例子

    语法 get()方法语法: dict.get(key, default=None) 参数 key -- 字典中要查找的键. default -- 如果指定键的值不存在时,返回该默认值值. 返回值 返回 ...

  3. python,栈的小例子

    ''' 1.首先确认栈的概念,先进后出 2.初始化的时候如果给了一个数组那么就要将数组进栈 ''' class Stack: def __init__(self,start=[]): self.sta ...

  4. [Spark][Python]Spark Join 小例子

    [training@localhost ~]$ hdfs dfs -cat people.json {"name":"Alice","pcode&qu ...

  5. python事件驱动的小例子

    首先我们写一个超级简单的web框架 event_list = [] #这个event_list中会存放所有要执行的类 def run(): for event in event_list: obj = ...

  6. 由Python的一个小例子想到的

    习题: L = [1,2] L.append(L) Print L 问,结果是什么. 结果是,[1,2,[...]] 这是什么意思呢?就是说[...]表示的对[1,2]的无限循环.这一点是在C#等静态 ...

  7. python 基础 字典 小例子

    统计单词次数 作为字典存储 cotent = "who have an apple apple is free free is money you know" result = { ...

  8. python 基础 列表 小例子

    存主机ip到列表 host_list=[] netip='192.168.1' for hostip in range(1,254): ip = netip +str(hostip) host_lis ...

  9. 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='') ...

  10. [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 ...

随机推荐

  1. js常用代码收集

    1. PC - js 返回指定范围的随机数(m-n之间)的公式 Math.random()*(n-m)+m return false return false // event.preventDefa ...

  2. Mybatis学习笔记(一) —— mybatis介绍

    一.Mybatis介绍 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名 ...

  3. C语言之基本编程思想与基本概念扫盲

    前言:C语言是包含了很多编程的基本思想,理解C能够有助于理解其他高级语言,深刻理解编程很多基本思想:这对新手入门是有很多好处的,正所谓磨刀不误砍柴工,内功与基础修炼扎实了,才能开始盖高楼大厦. 这篇文 ...

  4. 对bootstrap模态框的小尝试

    bootstrap中有一个“模态框”插件,我理解的意思就是一个具有全局遮罩的弹窗提示,官方解释是:模态框(Modal)是覆盖在父窗体上的子窗体.通常,目的是显示来自一个单独的源的内容,可以在不离开父窗 ...

  5. Experimental Educational Round: VolBIT Formulas Blitz K

    Description IT City company developing computer games decided to upgrade its way to reward its emplo ...

  6. day20 模块 collections time sys os

    1.模块 1. 模块的定义:我们把装有特定功能的代码进行归类的结果.我们目前写的所有py文件都是模块 2. 引入模块的方式: 1.import 模块名 2.from xxx import 模块名 2. ...

  7. Hive 报错信息及解决方法

    return code 2 为SQL报错. return code 1 一般为权限问题. 具体要看源码.

  8. ORA-1000的问题 Cursor 过多 (文档 ID 18591.1)

      #查看用户cursor的使用情况 col sid for a9999999999 col osuser for a20 col machine for a20 col num_curs for a ...

  9. JS中==、===和Object.is()的区别

    JS中==.===和Object.is()的区别 首先,先粗略了解一下这三个玩意儿: ==:等同,比较运算符,两边值类型不同的时候,先进行类型转换,再比较: ===:恒等,严格比较运算符,不做类型转换 ...

  10. 数据结构---Java---LinkedList

    public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, D ...