Py指令碼:轉換兩個檔案名稱

來源:互聯網
上載者:User

自己寫的一個簡單的交換兩個檔案(夾)的py指令碼,一開始本打算用shell寫的,後來趕腳自己的shell還是比較菜,不如python來的利索,於是py了。

代碼如下:

#!/usr/bin/env python# coding=utf-8# author:andrewallanwallace@gmail.com'''This simple script is written for easily swap two files or two folders.'''def swap(origin, dest, temp):    '''    Swap files     mv origin temp    mv dest origin    mv temp dest    '''    from os import system    origin2Temp = 'mv -f -v %s %s'%(origin, temp)    system(origin2Temp)        dest2Origin = 'mv -f -v %s %s'%(dest, origin)    system(dest2Origin)    temp2Dest = 'mv -f -v %s %s'%(temp, dest)    system(temp2Dest)def shouldSwap(origin, dest):    from os import path        originExists = path.exists(origin)    destExists = path.exists(dest)    if(not originExists or not destExists):        print 'Both the files should be existing %s existing State = %s ; %s existing State = %s'%(origin, str(originExists), dest, str(destExists))        return False         originIsDir = path.isdir(origin)    destIsDir = path.isdir(dest)    if (originIsDir != destIsDir):        print 'the two files should be the same type %s is dir = %s ;%s is dir = %s'%(origin, str(originIsDir), dest, str(destIsDir))        return False    return True        def main():    '''    Usage:swapf.py origin dest [temp]    '''    import sys    paramsSize = len(sys.argv)        origin = None    dest = None    temp = 'temp_backup.file'    if (paramsSize < 3):        print main.__doc__        return    origin = str(sys.argv[1])    dest = str(sys.argv[2])    if (paramsSize == 4):        temp = str(sys.argv[3])    if (shouldSwap(origin, dest)):        swap(origin, dest, temp)main()

使用方法

檔案:

swapf.py a.txt b.txt temp.txt

檔案夾

swapf.py folderA folderB tempFolder

第三個參數不需要添加也可以。

github地址:https://github.com/androidyue/little_works/blob/master/py_works/tools/swapf.py

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.