python获取文件后缀名及批量更新目录下文件后缀名的方法

本文实例讲述了python获取文件后缀名及批量更新目录下文件后缀名的方法。分享给大家供大家参考。具体实现方法如下:

1. 获取文件后缀名:


代码如下:

#!/usr/bin/python
import os
dict = {}
for d, fd, fl in os.walk('/home/ahda/Program/'):
        for f in fl:
                sufix = os.path.splitext(f)[1][1:]
                if dict.has_key(sufix):
                        dict[sufix] += 1
                else:
                        dict[sufix] = 1
for item in dict.items():
        print "%s : %s" % item

这里的关键是os.path.splitext()
如abc/ef.g.h ,这里获取到的是h

2. python查找遍历指定文件路径下指定后缀名的文件实例:


代码如下:

import os
import sys
import os.path
for dirpath, dirnames, filenames in os.walk(startdir):
        for filename in filenames:
            if os.path.splitext(filename)[1] == '.txt':
               filepath = os.path.join(dirpath, filename)
               #print("file:" + filepath)
               input_file = open(filepath)
               text = input_file.read()
               input_file.close()
              
               output_file = open( filepath, 'w')
               output_file.write(text)
               output_file.close()

3. 批量重命名目录中的文件后缀实例:


代码如下:

import os
def swap_extensions(dir, before, after):
    if before[:1] != '.': #如果参数中的后缀名没有'.'则加上
        before = '.' + before
    thelen = -len(before)
    if after[:1] != '.':
        after = '.' + after
    for path, subdir, files in os.walk(dir):
        for oldfile in files:
            if oldfile[thelen:] == before:
                oldfile = os.path.join(path, oldfile)
                newfile = oldfile[:thelen] + after
                os.rename(oldfile, newfile)
                print oldfile +' changed to ' + newfile
if __name__ == '__main__':
    import sys
    if len(sys.argv) != 4:
        print 'Usage:swap_extension.py rootdir before after'
        sys.exit(1)
    swap_extensions(sys.argv[1], sys.argv[2], sys.argv[3])

例子:将e:/py/test目录下.php结尾的文件重命名为.py
 
E:py>python_cook e:/py/test .php .py
e:/py/testtest.php changed to e:/py/testtest.py
e:/py/test1.php changed to e:/py/test1.py
e:/py/test2.php changed to e:/py/test2.py

希望本文所述对大家的Python程序设计有所帮助。

(0)

相关推荐

  • centos下更新Python版本的步骤

    安装完CentOS5.9(Final)后,执行#Python与#python -V,看到版本号是2.4.3,很老了,而且之前写的都是跑在python3.X上面的,3.X和2.X有很多不同,有兴趣的朋友可以参考下这篇文章: http://www.jb51.net/article/34011.htm 更新python千万不要把老版本的删除!新老版本是可以共存的,很多基本的命令.软件包都要依赖预装的老版本python的,比如yum. 更新python: 第1步:更新gcc,因为gcc版本太老会导致新版

  • 跟老齐学Python之使用Python查询更新数据库

    回顾一下已有的战果:(1)连接数据库;(2)建立指针:(3)通过指针插入记录:(4)提交将插入结果保存到数据库.在交互模式中,先温故,再知新. 复制代码 代码如下: >>> #导入模块 >>> import MySQLdb >>> #连接数据库 >>> conn = MySQLdb.connect(host="localhost",user="root",passwd="123123&

  • 在Python的Django框架中更新数据库数据的方法

    先使用一些关键参数创建对象实例,如下: >>> p = Publisher(name='Apress', ... address='2855 Telegraph Ave.', ... city='Berkeley', ... state_province='CA', ... country='U.S.A.', ... website='http://www.apress.com/') 这个对象实例并 没有 对数据库做修改. 在调用`` save()`` 方法之前,记录并没有保存至数据库,

  • Python编程实现双击更新所有已安装python模块的方法

    本文实例讲述了Python编程实现双击更新所有已安装python模块的方法.分享给大家供大家参考,具体如下: 首先声明我是一个升级控.几乎每天会查看一下手机.电脑是否有新的应用需要更新. 同样,我的python模块也是这样.百度了一下,发现目前还没有人将更新所有模块做成一件命令,但是查到了指引,主要就是两个命令. pip list --outdated pip install -U xxxx 当然,如果你只是安装了几个python模块,重复执行几次命令也是可以的,也不会太烦,也不会浪费时间. 有

  • Python常用模块介绍

    python除了关键字(keywords)和内置的类型和函数(builtins),更多的功能是通过libraries(即modules)来提供的. 常用的libraries(modules)如下: 1)python运行时服务 * copy: copy模块提供了对复合(compound)对象(list,tuple,dict,custom class)进行浅拷贝和深拷贝的功能. * pickle: pickle模块被用来序列化python的对象到bytes流,从而适合存储到文件,网络传输,或数据库存

  • 跟老齐学Python之玩转字符串(2)更新篇

    上一章中已经讲到连接两个字符串的一种方法.复习一下: 复制代码 代码如下: >>> a= 'py' >>> b= 'thon' >>> a+b 'python' 既然这是一种方法,言外之意,还有另外一种方法. 连接字符串的方法2 在说方法2之前,先说明一下什么是占位符,此前在讲解变量(参数)的时候,提到了占位符,这里对占位符做一个比较严格的定义: 来自百度百科的定义: 顾名思义,占位符就是先占住一个固定的位置,等着你再往里面添加内容的符号. 根据这个定

  • Linux更新Python版本及修改python默认版本的方法

    linux下更新Python版本并修改默认版本,有需要的朋友可以参考下. 很多情况下拿到的服务器python版本很低,需要自己动手更改默认python版本 1.从官网下载python安装包(这个版本可以是任意版本3.3 2.7 2.6等等) wget http://python.org/ftp/python/2.7/Python-2.7.tar.bz2 2.解压并安装 tar -jxvf Python-2.7.tar.bz2 cd Python-3.3.0 ./configure make al

  • python通过pip更新所有已安装的包实现方法

    较新的pip已经支持list --outdated了,所以记录一下新的方法: pip list --outdated --format=legacy |awk '{print $1}' |xargs sudo -H pip install -U pip3 list --outdated --format=legacy |awk '{print $1}' |xargs sudo -H pip3 install -U format有两个选项,一个是legacy,一个是columns.后者会带一个表头

  • python实现dnspod自动更新dns解析的方法

    复制代码 代码如下: def ddns():"""用当前ip更新ddns"""headers = {"Content-type": "application/x-www-form-urlencoded", "Accept": "text/json"}conn = httplib.HTTPSConnection("dnsapi.cn", timeou

  • python更新列表的方法

    本文实例讲述了python更新列表的方法.分享给大家供大家参考.具体如下: aList = [123, 'abc', 4.56, ['inner', 'list'], (7-9j)] print aList[2] aList[2] = 'float replacer' print aList aList.append("hi, i'm new here") print aList 运行结果如下: 4.56 [123, 'abc', 'float replacer', ['inner',

随机推荐