python - write() 写入的文件无法在 Windows 中打开

标签 python web.py

代码在这里:

#!/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/

相关文章:

python - pandas 数据框中的颜色数字

python - CookieError : Illegal key value

python - 类型错误 : can't pickle file objects webpy and subprocess

python - web.py 不会删除请求之间的停止

python - 在 web.py 中异步发送邮件

python - 操作数不能与形状(299,491)(299,491,3)一起广播。如何解决像素乘法?

python - 如何在函数中将列表转换为数组 - python?

python - 制作 0 到 nxn 矩阵并将其 reshape 为对

python - POST 处理程序返回的页面被忽略 - 得到空白响应 (web.py)

python - 对复合 sqlalchemy 查询的顺序有任何性能影响吗?