我试图弄清楚如何打开,操作和重新保存一个上传的文件在烧瓶。我已经得到它,所以我可以上传文件,但打开它,并做我想要的数据是不会发生的。
这是我拥有的..。
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文件..。
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)提前感谢!
发布于 2014-06-01 09:36:36
您已经嵌套了语句,您在外部语句中打开的文件需要先关闭,然后才能再次打开它以便写入:
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您也不需要保存它,因为一旦执行循环正文中的所有语句,循环将关闭(即保存并写入磁盘)文件。
https://stackoverflow.com/questions/23978469
复制相似问题