利用Python做工具-2__Python

來源:互聯網
上載者:User

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




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.