我尝试使用python来处理文本替换问题。有一个小端的UTF-16格式的文件,我想替换这个文件中的ip地址。首先,我逐行读取这个文件,然后替换目标字符串,最后,我将新字符串写入该文件。但多线程操作此文件时,文件将被弄乱。这是我的密码。在
import re
import codecs
import time
import thread
import fcntl
ip = "10.200.0.1"
searchText = r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"
def replaceFileText(fileName,searchText,replaceText,encoding):
lines = []
with codecs.open(fileName,"r",encoding) as file:
fcntl.flock(file,fcntl.LOCK_EX)
for line in file:
lines.append(re.sub(searchText,replaceText,line))
fcntl.flock(file,fcntl.LOCK_UN)
with codecs.open(fileName,"w",encoding) as file:
fcntl.flock(file,fcntl.LOCK_EX)
for line in lines:
file.write(line)
fcntl.flock(file,fcntl.LOCK_UN)
def start():
replaceFileText("rdpzhitong.rdp",searchText,ip,"utf-16-le")
thread.exit_thread()
def test(number):
for n in range(number):
thread.start_new_thread(start,())
time.sleep(1)
test(20)
我不明白为什么文件会乱码,我用fcntl flock来保持读/写顺序,问题在哪里?在
它是乱码的,因为fcntl锁由进程拥有,而不是由线程拥有,因此进程不能使用fcntl序列化自己的访问。例如,请参见this answer。在
您需要使用类似Lock的线程结构。在
我想它是乱七八糟的,因为你打开它后就把它锁上了。在这种情况下,seek位置可能是错误的。在
顺便说一句,Python中的线程在这种情况下没有那么有用(看看pythongil问题)。我建议您使用multiprocessing模块,并使用队列/管道更改逻辑,使分析数据的工作进程和负责输入和输出文件的I/O的主进程成为可能。在
相关问题 更多 >
编程相关推荐