Python中讀寫文件操作

   文件讀寫在Python程序或者工具中經常使用。

#!/usr/bin/python
import os
def sha1Reader(sha1ListPath):
    sha1List = None
    try:
        sha1Reader = open(sha1ListPath, "r")
        sha1List = sha1Reader.readlines()
        sha1Reader.close()
        return sha1List
    except Exception, exInfo:
        print "READ ERR [%s]" %exInfo
    return sha1List
def sha1Writer(sha1ListPath,content):
    try:
        sha1Writer = open(sha1ListPath, "a+")
        sha1Writer.writelines(content+"\n")
        sha1Writer.close()
    except Exception, exInfo:
        print "WRITE ERR [%s]" %exInfo
        return False
    return True
def sort(sha1Folder, outFolder):
    sha1ItemFolderList = os.listdir(sha1Folder)
    for sha1ItemTxt in sha1ItemFolderList:
        sha1TxtPath = os.path.join(sha1Folder, sha1ItemTxt)
        sha1List = sha1Reader(sha1TxtPath)
        sha1Set = {}
        for sha1Line in sha1List:
            try:
                sha1Line = sha1Line.strip()
                lineItemList = sha1Line.split('\t')
                if len(lineItemList) != 3:
                    print "Err line: [%s]" %sha1Line
                    continue
                sha1 = lineItemList[0]
                package = lineItemList[1]
                version = int(lineItemList[2])
                updateFlag = True
                if sha1Set.has_key(package) \
                   and sha1Set[package][0] >= version:
                    updateFlag = False
                if updateFlag:
                    content = [version, sha1]
                    sha1Set[package] = content
            except Exception, exInfo:
                print "PARSE [%s] ERR [%s]" %(sha1Line,exInfo)
        outTxt = os.path.join(outFolder, sha1ItemTxt)
        for key in sha1Set:
            print "%s,%s,%s" %(key, \
                   sha1Set[key][1], \
                   sha1Set[key][0])
            content = sha1Set[key][1]
            sha1Writer(outTxt,content)
if __name__ == "__main__":
    pkgFolder = "./TopPackage"
    sha1Folder = "./Sha1"
    sort(pkgFolder, sha1Folder)

以上是工作中使用到的一個Python腳本,記錄於此以方便日後參考。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章