我尝试使用python来处理文本替换问题。有一个Little-endian 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集群来保持读/写顺序,问题出在哪里?
最佳答案
这是乱码,因为 fcntl 锁属于进程,而不是线程,因此进程无法使用 fcntl 来序列化自己的访问。请参阅this answer ,例如。
您需要使用线程构造,例如 Lock相反。
关于python 多线程使用 fcntl flcok 处理文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17748450/