小诺爷 发表于 2020-7-22 22:44:43

来个大佬帮忙看下代码

temp_1 = input('请输入需要比较的头一个文件名:') #接收用户输入
temp_2 = input('请输入需要比较的另一个文件名:')

def guess(temp_1,temp_2):
    po_1 = 'E:\\'+temp_1+'.txt'
    po_2 = 'E:\\'+temp_2+'.txt'
    w = []
    count = 1
    temp1 = open(po_1,mode='r',encoding='utf-8')
    temp2 = open(po_2,mode='w',encoding='utf-8')
    for i in temp1:
      a =temp2.readline()
      count += 1
      if temp1 != a:
            w.append(count)
            continue
    temp1.close()
    temp2.close()
    print('文件共有%d处不同'% len(w))
    for e in w:
      print('第%d行不同'% e)
guess(temp_1,temp_2)

为上面我执行起来会总是显示0处不同呢我想知道哪一步出了毛病
另外里面的这段代码我始终搞不明白上面意思
readline() 不是写入模式打开吗这里循环会一行一行的循环里面的内容吗?
    for i in temp1:
      a =temp2.readline()
      count += 1
      if temp1 != a:
            w.append(count)
            continue

Twilight6 发表于 2020-7-22 22:48:21



代码改成这样,把 if temp1 != a 改成 if i != a 即可:

temp_1 = input('请输入需要比较的头一个文件名:') #接收用户输入
temp_2 = input('请输入需要比较的另一个文件名:')

def guess(temp_1,temp_2):
    po_1 = 'E:\\'+temp_1+'.txt'
    po_2 = 'E:\\'+temp_2+'.txt'
    w = []
    count = 1
    temp1 = open(po_1,mode='r',encoding='utf-8')
    temp2 = open(po_2,mode='w',encoding='utf-8')
    for i in temp1:
      a =temp2.readline()
      count += 1
      if i != a:
            w.append(count)
            continue
    temp1.close()
    temp2.close()
    print('文件共有%d处不同'% len(w))
    for e in w:
      print('第%d行不同'% e)
guess(temp_1,temp_2)

readline() 不是写入模式打开吗这里循环会一行一行的循环里面的内容吗?

readline() 是读取文件的一行内容, open 的 'w' 才是以写入模式打开,for 每循环一次 readline() 读取文件一行内容

小诺爷 发表于 2020-7-22 22:55:43

okok
谢谢
页: [1]
查看完整版本: 来个大佬帮忙看下代码