我在分析上传到我的服务器的文件时遇到问题。理想情况下,用户会上传一个 .csv,我将从文件中的数据运行一些数字集成(因此 import numpy as np
)并返回结果。为了在进行任何分析之前测试 cgi 部分,我在下面制作了 python 脚本。我的问题是消息总是显示为空白,所以最后我在浏览器中显示了一个空白的 html 页面。
显然我没有正确读取文件(这意味着我无法分析它),但我不知道我做错了什么。我自己的搜索表明我下面的内容应该有效。
#!/usr/bin/python
#---------------------------------------------
#=============================================
#---------------------------------------------
#imports
#import csv
#import time as tm
#import numpy as np
#import os
import cgi, cgitb
cgitb.enable()
form = cgi.FieldStorage()
#The variables
#httpopen=""
#httpclose=""
message="meow"
#get the fileitem
fileitem=form['userfile']
if fileitem.file:
#yay...we got a file
message=fileitem.file.readline()
print """\
Content-Type: text/html\n
<html><body>
<p>%s</p>
</body></html>
""" % (message,)
这是提供上传的 html 表单:
<html>
<body>
<form enctype="multipart/form-data"
action="capacity_rewrite.py" method="post">
<p>File: <input type="file" name="userfile" /></p>
<p><input type="submit" value="Upload" /></p>
</form>
</body>
</html>
谢谢,
最佳答案
您只阅读了上传文件中的一行。也许第一行是一个空行?请尝试使用 fileitem.file.read()
,它将整个文件读入一个字符串。不要对大文件执行此操作,因为您可能会耗尽内存,但这应该有助于理解您的测试。
关于python - 在 Python 中读取通过 CGI 上传的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13275657/