python - 如何在差异函数的 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()
解决方案
您应该通过文件名而不是文件对象打开文件:
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)
推荐阅读
- php - 检查两个集合的差异
- android - 启用远程js调试时React Native应用程序没有网络连接
- angular - Mat datepicker 仅格式化多个选择器之一
- php - 如何将输入限制为两倍?
- vb.net - 我需要帮助将此 C# Linq 查询转换为 VB.net。我不太了解某些方面
- flutter - 为什么 SearchDelegate 的 buildSuggestion 方法不起作用?
- java - 使用哈希映射(键/值对)处理帖子表单的成语
- artifactory - Artifactory OSS版无维护操作
- angular - 当我在 Angular 中导航到其路由的子子项时,如何保持 mat-tab 处于活动状态?
- spring - Spring 工具套件:非空属性引用空值或瞬态值