TypeError:“in<string>”需要字符串作为左操作数,而不是in

2024-04-27 04:59:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我比较两个文件,并删除重复的第二个文件。但是扔错了

2个文件。需要在第一行的最后添加一个数字并附加到file2.txt中。但是如果修改的部分已经存在,那么file2保持不变

import re
import sys
file1 = sys.argv[1]
file2 = sys.argv[2]
rx = r'(?<=:)(\d*)$'
with open(file1,'r') as fh:
    fh_n = fh.read()
    with open(file2, 'a+') as fw:
        x = fw.write(re.sub(rx , lambda x: str(int(x.group(0)) + 1) if len(x.group(1)) else "0", fh_n, 1, re.M))
        if x not in file2:
            fw.write(x)

文件1.txt

python 2.7:
  Java 1.8:

python test.py file1.txt file2.txt

即使在这么多的处决之后,我也期待着离开

 python 2.7:0
      Java 1.8:

我得到了错误回溯(上次的最新呼叫): “文件”文件.py“,第15行,in 如果x不在文件2中: TypeError:“in”需要字符串作为左操作数,而不是int


Tags: 文件inimportretxtaswithsys
1条回答
网友
1楼 · 发布于 2024-04-27 04:59:49

您需要读取file2的内容才能在其中搜索x。您的代码应该是:

import re
import sys
import os
file1 = sys.argv[1]
file2 = sys.argv[2]
rx = r'(?<=:)(\d*)$'
with open(file1,'r') as fh:
    fh_n = fh.read()
    with open(file2, 'a+') as fw:
        x = re.sub(rx , lambda x: str(int(x.group(0)) + 1) if len(x.group(1)) else "0", fh_n, 1, re.M)
        fw.seek(0, os.SEEK_SET)      # seek to the beginning of file before reading
        if x not in fw.read():
            fw.seek(0, os.SEEK_END)  # seek to end of file before writing
            fw.write(x)

我添加了seek调用,因为在读写操作之间需要它们。你知道吗

相关问题 更多 >