您的位置:首页 > 移动开发

Swapping One File Extension for Another Throughout a Directory Tree

2019-08-01 21:24 1806 查看
原文链接:https://www.geek-share.com/detail/2446201400.html

Problem

You need to rename files throughout a subtree of directories, specifically changing the names of all files with a given extension so that they have a different extension instead.

Solution

Operating on all files of a whole subtree of directories is easy enough with the os.walk function from Python's standard library:

SwapExtensions
 1 >>> import os
 2 >>> def swapextensions(dir, before, after):
 3     if before[:1] != '.':
 4         before = '.'+before
 5     length = -len(before)
 6     if after[:1] != '.':
 7         after = '.'+after
 8     for path, dirs, files in os.walk(dir):
 9         for oldfile in files:
10             if oldfile[length:] == before:
11                 oldfile = os.path.join(path, oldfile)
12                 newfile = oldfile[:length] + after
13                 os.rename(oldfile, newfile)

 

Usage

Before swap:

Before swap
1 >>> for path, dirs, files in os.walk('c:\\Test'):
2     for f in files:
3         print f
4
5         
6 3545.csv
7 abc.txt
8 e.xml

 

Swap:

Swap
1 >>> swapextensions('c:\\Test', 'txt', 'csv')

 

After swap:

After swap
1 >>> for path, dirs, files in os.walk('c:\\Test'):
2     for f in files:
3         print f
4
5         
6 3545.csv
7 abc.csv
8 e.xml

 

 

转载于:https://www.cnblogs.com/zhtf2014/archive/2009/02/21/1395440.html

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐