gpt4 book ai didi

python - 如何更新用户输入给出的 csv 文件的字段名?

转载 作者:行者123 更新时间:2023-11-28 00:53:18 24 4
gpt4 key购买 nike

我正在尝试构建一个应用程序,该应用程序采用具有不同列数的不同 CSV 文件。例如,我的 CSV 文件有大约 30 列,其字段名称具有特殊字符。所以,我想更新用户给出的字段名称。我有一个 CSV 文件,看起来像这样:

ques.1,ques.2
3,5
5,1

我想用用户提供的标题(电视、广播)更新列名称 ques.1、ques.2

python :

def upload():
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
file = request.files['file']

# if user does not select file, browser also
# submit a empty part without filename
if file.filename == '':
flash('No selected file')
return redirect(request.url)

if file and allowed_file(file.filename):
app.logger.info('File Saved')

filename = secure_filename(file.filename)
savepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
flash(savepath)
file.save(savepath)

save_in(savepath)

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

return render_template('pages/placeholder.upload.html')

def save_in(savepath):
app.logger.info(savepath)

csv_rows = []

with open(savepath) as csvfile:
reader = csv.DictReader(csvfile)
title = reader.fieldnames
for row in reader:
csv_rows.extend([{title[i]:row[title[i]] for i in range(len(title))}])

我试图在选择菜单中填充字段名称。但我不知道如何让用户:

  1. 从选择菜单中选择要更新的字段名称。
  2. 输入新的字段名称。
  3. 单击“更新”按钮更改字段名称。

HTML

<div class="container">
<form class="col s12" action="/upload" method="POST" enctype="multipart/form-data">
<div class="row">
<div class="input-field col s12 m6">
<label>Update Fieldnames</label>
<select class="icons">
{% for x in title %}
<option value="{{ x }}"{% if loop.first %} SELECTED{% endif %}>{{ x }}</option>
{% endfor %}
</select>
<button class="btn" type="submit" value="Update">Submit</button>
</div>
</div>
</form>
</div>

最佳答案

模板

如前评论所述,您应该将选择菜单替换为 label 和文本 input 的列表(在 html 模板中)。这使您和主要是用户的过程变得更加容易,他们可以更新所有字段,而不是一个一个地编辑它们。

文本输入可以通过包含循环索引的名称来标识,因此您可以匹配 POST 请求中的原始字段(即使两个字段名相同)。默认值为原始标题,因此用户可以保留或修改。

显示示例:

Field 1 : Title1
Field 2 : Title2

<div class="container">
<form class="col s12" action="/update" method="POST" enctype="multipart/form-data">
<div class="row">
<h2>Update Fieldnames</h2>
{% for x in title %}
<label> Field {{ loop.index }} : </label>
<input type="text" name="field-{{ loop.index }}" value="{{ x }}" ></input>
<br>
{% endfor %}
<input type="hidden" name="filename" value= {{filename}}></input>
<button class="btn" type="submit" value="Update">Submit</button>
</div>
</form>
</div>

文件名被添加为表单中的隐藏输入,以便能够在 View 中访问文件,并处理字段更新。

这需要在render_template语句中添加变量:

return render_template('main.html', title=data, filename=savepath) #according to the variable in the function save_in()

View

然后 update View 可以获取 request.form 值并创建一个新的字段名列表。

@app.route("/update", methods=['POST'])
def update():
filepath = request.form['filename']
newtitles = []
for index in range(1, len(request.form)): # begin at 1 and leave filename out
newtitles.append(request.form.get('field-' + str(index)))

rows = [newtitles] # stores the new header

with open(filepath, 'r') as csv_in :
reader = csv.reader(csv_in)
next(reader, None) # ignores the original header
for row in reader:
rows.append(row) # stores all rows

with open(filepath, 'w') as csv_out:
writer = csv.writer(csv_out)
writer.writerows(rows) # writes all rows, including new header

return """<html><div>New titles updated: {} to the file {}</div></html>""".format(newtitles, filepath)

该文件已被新版本替换,需要多行几行才能实现,但如果您更喜欢保留原始版本,您可以从 this post 中获得一些灵感。 .

关于python - 如何更新用户输入给出的 csv 文件的字段名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46084145/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com