首页 > 解决方案 > 如何在差异函数的 1 个变量下打开两个同名文件?

问题描述

我做了 2 个循环,必须打开 2 个相同的文件名 req.txt。我只想输入 1 个文件,但由两个循环读取。我在下面做了但无效..错误消息

第 32 行,在 open(requestfile,'r') as rqfile: TypeError: coercing to Unicode: need string or buffer, file found

onefile= './req.txt'
with open(onefile, 'r') as requestfile:
#rqfile = rrr = requestfile

    with open(requestfile,'r') as rqfile:
        for line in rqfile:           
            line = line.rstrip()        
            if line.startswith('Referer: '): 
                urll = line[9:]      
            elif line.startswith('Cookie: '):
                cookie=line[18:]
            elif line.startswith('Host: '):
                host=line[6:]

    rqfile.close()

with open(requestfile,'r') as rrr:
    for i, line in enumerate(rrr):  

        if i == 14:

            username = line[:line.index('=')]
            password = line[line.index('&') + 1:line.index('=', line.index('=') + 1)]
                print(username, password)
rrr.close()

标签: pythonfilevariablesinput

解决方案


您应该通过文件名而不是文件对象打开文件:

onefile = './req.txt'

with open(onefile, 'r') as rqfile:
    for line in rqfile:  # loop over the file directly
        line = line.rstrip()  # remove the trailing newline
        if line.startswith('Referer: '):  # start cari text tertentu
            urll = line[9:]  # get text start with lajur 9
        elif line.startswith('Cookie: '):
            cookie = line[18:]
        elif line.startswith('Host: '):
            host = line[6:]

with open(onefile, 'r') as rrr:
    for i, line in enumerate(rrr):
        if i == 14:
            username = line[:line.index('=')]
            password = line[line.index('&') + 1:line.index('=', line.index('=') + 1)]
            print(username, password)

推荐阅读