Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/337.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用Dash上传、处理和下载.csv文件?_Python_Pandas_Csv_Web Applications_Plotly - Fatal编程技术网

Python 如何使用Dash上传、处理和下载.csv文件?

Python 如何使用Dash上传、处理和下载.csv文件?,python,pandas,csv,web-applications,plotly,Python,Pandas,Csv,Web Applications,Plotly,我正试图用Dash编写一个简单的web应用程序,用户上传一个csv文件,用pandas在数据框中完成一些处理,然后用户可以通过链接下载新的csv文件。虽然我在数据分析方面做得不错,但我还是个新手。这可能是超基本的,但我不知道熊猫处理部分应该去哪里,以及最终如何生成下载链接 以下是代码的简化版本: import base64 import datetime import io import dash from dash.dependencies import Input, Output, St

我正试图用Dash编写一个简单的web应用程序,用户上传一个csv文件,用pandas在数据框中完成一些处理,然后用户可以通过链接下载新的csv文件。虽然我在数据分析方面做得不错,但我还是个新手。这可能是超基本的,但我不知道熊猫处理部分应该去哪里,以及最终如何生成下载链接

以下是代码的简化版本:

import base64
import datetime
import io


import dash
from dash.dependencies import Input, Output, State
import dash_core_components as dcc
import dash_html_components as html

import pandas as pd

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)

app.layout = html.Div(children = [
    html.H2('Please upload your csv file:'),
    dcc.Upload(
        id= 'upload-data', 
        children = html.Div([
            html.A('Select File')]),
        style = {
            'width': '100%',
            'height': '60px',
            'lineHeight': '60px',
            'borderWidth': '1px',
            'borderStyle': 'dashed',
            'borderRadius': '4px',
            'textAlign': 'center',
            'margin': '5px'
        }, 
    ),
    html.Div(id='download-link') 
    ])


def parse_contents(contents, filename):
    content_type, content_string = contents.split(',')

    decoded = base64.b64decode(content_string)
    try: 
        if 'csv' in filename:
            # Assume the uploaded file is csv 
            df = pd.read_csv(io.StringIO(decoded.decode('utf-8')))
    except Exception as e:
        print(e)
        return html.Div([
            'There was an error. Please uplaod the file in csv format.'
            ])
    return df


@app.callback(Output('download-link', 'href'),
    [Input('upload-data', 'contents')])

# Data processing using pandas:

def example_func(df):
    df['col2'] = df['col1']+'some string'
        return df

df_new = df.apply(example_func, axis=1)
df_new.to_csv('processed_data.csv')

# Return a link to let the user download the csv file with the processed data
def download_csv (contents):
    #######

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

任何意见都将不胜感激

首先,您需要导入这些额外的库:

import os
from urllib.parse import quote as urlquote
定义文件的位置:

UPLOAD_DIRECTORY = "/project/app_uploaded_files"

if not os.path.exists(UPLOAD_DIRECTORY):
    os.makedirs(UPLOAD_DIRECTORY)
添加以下功能:

def save_file(name, content):
    """Decode and store a file uploaded with Plotly Dash."""
    data = content.encode("utf8").split(b";base64,")[1]
    with open(os.path.join(UPLOAD_DIRECTORY, name), "wb") as fp:
        fp.write(base64.decodebytes(data))

def uploaded_files():
    """List the files in the upload directory."""
    files = []
    for filename in os.listdir(UPLOAD_DIRECTORY):
        path = os.path.join(UPLOAD_DIRECTORY, filename)
        if os.path.isfile(path):
            files.append(filename)
    return files

def file_download_link(filename):
    """Create a Plotly Dash 'A' element that downloads a file from the app."""
    location = "/download/{}".format(urlquote(filename))
    return html.A(filename, href=location)
您可以在此处找到完整的代码:


希望有帮助

您需要将数据处理放在上传回调中。对于下载,它必须在客户端完成。有关复制粘贴解决方案,请参见。