Python Windows多个程序员同时运行到同一文件

时间:2019-02-18 15:47:56

标签: python io

我需要在同一个文本文件中为多个程序写入文本日志文件,我以为我需要某种锁定机制,但是后来我写了一个简单的多线程,并注意到某些日志没有写到最终目录文本文件?

def abc1Thread():
    import portalocker
    print ("-----------------abc1-Thread --------------------")
    g = open("testFile", "a")
    cnt = 0
    f1 = open("A.txt", "a")
    while (True):
        cnt = cnt+1
        if cnt == 10: break
        print ("abc1Thread: cnt --> ",cnt+1)
        f1.write("abc1Thread: cnt --> "+ str(cnt)+ "\n")

    print ("close file handle: "+ str(f1))
    f1.close()

def abc2Thread():
    import portalocker
    print("-----------------abc2-Thread --------------------")
    cnt = 0
    f2 = open("A.txt", "a")
    while (True):
        cnt = cnt+1
        if cnt == 10: break
        print("abc2Thread: cnt --> ", cnt)
        f2.write("abc2cThread: cnt --> "+str(cnt)+"\n")

    print ("close file handle: "+ str(f2))
    f2.close()


def fileWriteShare():
    thrd1 = threading.Thread(target=abc1Thread, args=[])
    thrd2 = threading.Thread(target=abc2Thread, args=[])
    thrd1.start()
    thrd2.start()

如何在Windows python中锁定和解锁到文本文件,以便所有程序都能可靠地写入