Django前端上传txt/log文件:
```html
<input type="file" name="e_file">
<input type="submit" name="提交">
**views.py文件里:**
log_Pattern = r'^(?P<remote_addr>.*?) - (?P<remote_user>.*) \[(?P<time_local>.*?)\] "(?P<request>.*?)" ' \
'(?P<status>.*?) (?P<body_bytes_sent>.*?) "(?P<http_referer>.*?)" "(?P<http_user_agent>.*?)"$'
file = request.FILES['e_file']
with open(file, 'r', encoding='utf-8') as f:
for line in f:
m = re.findall(log_Pattern, str(line), re.S)
data.append(m)
这里with open(file, 'r', encoding='utf-8') as f:
报错TypeError: expected str, bytes or os.PathLike object, not InMemoryUploadedFile
请问应该怎么改呢,改完还是能够按照log_Pattern做匹配读取文件内容到data列表里
出现此错误是因为open()
函数期望接收一个文件路径(字符串)、字节或类似于路径的对象(os.PathLike
),而不是InMemoryUploadedFile
对象。
要解决这个问题,可以使用TextIOWrapper
来处理InMemoryUploadedFile
对象,以便将其包装为可以用于读取的文件对象。下面是修改后的代码示例:
import io
# ...
file = request.FILES['e_file']
with io.TextIOWrapper(file, encoding='utf-8') as f:
for line in f:
m = re.findall(log_Pattern, line, re.S)
data.append(m)
在上述代码中,用了io.TextIOWrapper
来将InMemoryUploadedFile
对象 file
包装为可读取的文件对象 f
。然后,我们可以按照之前的代码逻辑继续处理文件内容并将匹配的结果添加到 data
列表中。
不再需要使用 str()
来处理每行内容,因为 TextIOWrapper
提供的对象已经是字符串形式。