前面用Python做了中文提取工具,现在再做一个复制文件的小工具,比较记录如下:
需求描述:
要求再一个固定的文件夹下不断的生成一些固定文件名的文件,供主程序去操作,给主程序进行压力测试。
需求解析:
最简单的就是把一个源文件夹(srcfile)中的不断的移动到目标文件夹(dstfile)
解决方案:
为了尽可能的简洁通用,这里还是使用配置文件作为输入变量的依据。不多说,上代码:
配置文件:config_copy.ini如下:
Python实现代码如下:
Python Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# -*- coding: utf-8 -*- #!/usr/bin/python # filename: copyfile.py # codedtime:2015-5-6 import os import shutil import configparser def excute(): iniconf = configparser.ConfigParser() iniconf. read( 'config_copy.ini') sourceDir = iniconf. get( 'setting', 'sourceDir') targetDir = iniconf. get( 'setting', 'targetDir') while True: for file in os.listdir(sourceDir): sourceFile = os.path. join(sourceDir, file) targetFile = os.path. join(targetDir, file) if not os.path.exists(targetFile): shutil.copyfile(sourceFile, targetFile) if __name__ == '__main__': excute() |
心得体会:
1、python之所以效率高,就在于有那么多现成的模块如: shutil、configparser等供你去使用,自己只要动手组织起来就可以了。
2、C++几个小时搞不定的东西,Python可能只需要几分钟就搞定,做一些小工具,着实方便,可爱的Python!!!
值得注意的地方:
1、 shutil.copyfile抛出异常:
异常分析:
解决办法: