首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >烧瓶文件操作

烧瓶文件操作
EN

Stack Overflow用户
提问于 2014-06-01 09:32:44
回答 1查看 1K关注 0票数 0

我试图弄清楚如何打开,操作和重新保存一个上传的文件在烧瓶。我已经得到它,所以我可以上传文件,但打开它,并做我想要的数据是不会发生的。

这是我拥有的..。

代码语言:javascript
复制
with open(os.path.join(app.config['UPLOAD_FOLDER'], filename), 'r') as f:
    content = f.read()
    with open(os.path.join(app.config['UPLOAD_FOLDER'], filename), 'wb') as outputFile:
        outputFile.write(content.lower())
        outputFile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

这是整个app.py文件..。

代码语言:javascript
复制
import os
from flask import *
from werkzeug import secure_filename

# Initialize the Flask application
app = Flask(__name__)
app.secret_key = '1234'

app.config['UPLOAD_FOLDER'] = 'uploads/'
app.config['ALLOWED_EXTENSIONS'] = set(['txt'])

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in app.config['ALLOWED_EXTENSIONS']

@app.route('/')
def index():
    return render_template('index.html')

# Route that will process the file upload
@app.route('/upload', methods=['POST'])
def upload():
    # Get the name of the uploaded file
    file = request.files['file']
    # Check if the file is one of the allowed types/extensions
    if file and allowed_file(file.filename):
        # Make the filename safe, remove unsupported chars
        filename = secure_filename(file.filename)

        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        # Redirect the user to the uploaded_file route, which
        # will basicaly show on the browser the uploaded file

        with open(os.path.join(app.config['UPLOAD_FOLDER'], filename), 'r') as f:
            content = f.read()
            with open(os.path.join(app.config['UPLOAD_FOLDER'], filename), 'wb') as outputFile:
                    outputFile.write(content.lower())
                    outputFile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))

    return redirect(url_for('uploaded_file', filename=filename))

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'], filename)


if __name__ == '__main__':
    app.run(debug=True)

提前感谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-06-01 09:36:36

您已经嵌套了语句,您在外部语句中打开的文件需要先关闭,然后才能再次打开它以便写入:

代码语言:javascript
复制
with open(os.path.join(app.config['UPLOAD_FOLDER'], filename), 'r') as f:
    content = f.read()

# At this point, the file is closed
with open(os.path.join(app.config['UPLOAD_FOLDER'], filename), 'wb') as output:
    # do stuff

您也不需要保存它,因为一旦执行循环正文中的所有语句,循环将关闭(即保存并写入磁盘)文件。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23978469

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档