前面用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拋出異常:
異常分析:
解決辦法: