代码在这里:
#!/usr/bin/env python
#-*-coding:utf-8 -*-
import web
urls=('/','index')
class index:
def GET(self):
web.header("Content-Type","text/html; charset=utf-8")
return """<html><head></head><body>
<form method="POST" enctype="multipart/form-data" action="">
<input type="file" name="mainTable" />
<br/>
<input type="submit" />
</form>
</body></html>"""
def POST(self):
i=web.input(mainTable={})
fout=open(".\\tables\\main.xls",'w')
fout.write(i.mainTable.file.read())
fout.close()
if __name__=="__main__":
app=web.application(urls,globals())
app.run()
我把它放在linux服务器上,它可以工作,excel文件上传成功(当然路径格式必须更改),我可以下载它并用excel打开它。
但是当我把它放在Windows服务器上时,文件已上传,但我无法打开它。 Excel显示文件已损坏。那么我的代码有什么问题吗?
最佳答案
来自the docs
The default is to use text mode, which may convert
'\n'
characters to a platform-specific representation on writing and back on reading. Thus, when opening a binary file, you should append'b'
to the mode value to open the file in binary mode, which will improve portability. (Appending'b'
is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.)
fout=open(".\\tables\\main.xls", 'wb')
关于python - write() 写入的文件无法在 Windows 中打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25277207/