TypeError:'in <string>'需要字符串作为左操作数而不是int

时间:2019-07-02 14:17:08

标签: python file if-statement

我正在比较2个文件,并从第二个文件中删除重复的文件。但是抛出错误

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)

file1.txt

python 2.7:
  Java 1.8:

python test.py file1.txt file2.txt

即使执行了那么多次,还是会出乎意料

 python 2.7:0
      Java 1.8:

我收到错误回溯(最近一次通话最近):   文件“ file.py”,第15行     如果x不在file2中: TypeError:'in'要求将字符串作为左操作数,而不是int

1 个答案:

答案 0 :(得分:2)

您需要阅读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个调用,因为在读和写操作之间需要它们。