【问题标题】:Export csv to a particular folder using URL & file path in python使用 python 中的 URL 和文件路径将 csv 导出到特定文件夹
【发布时间】:2020-12-12 04:33:15
【问题描述】:

我需要将我的 pandas 数据框作为 csv 导出到文件夹中。我的 python 解决方案部署在 IIS 服务器上,在那里我得到“file_path”和 url,我使用这两件事来获取或读取我的文件。 这是我为读取传入文件所做的。

from urllib.parse import quote

url = "http://20.9.6.11:8066" -- given
file_path = "file_upload/file_info/products/class1/file.csv" --given
incoming_file_path = url + "/" + quote(file_path)
df = pd.read_csv(incoming_file_path)

我可以使用上面的代码成功地获取或读取我的 csv 文件,但是在我的数据被处理之后 我需要将该 csv 导出到我无法导出的其他文件夹。我做到了:

folder_to_export_path = "http://20.9.6.11:8066/file_info/products/processed_file"
clean_df.to_csv(r'folder_to_export_path+'filename.csv') # error

【问题讨论】:

  • 你遇到什么错误?
  • @ChandanKumar 我试过了,出现以下错误:OSError: [Errno 22] Invalid argument: '20.9.6.11:8066/file_info/products/processed_file/filename.csv'

标签: python python-3.x pandas dataframe iis


【解决方案1】:

试试这个:

folder_to_export_path = "http://20.9.6.11:8066/file_info/products/processed_file/"
clean_df.to_csv(folder_to_export_path+'filename.csv')

参考:here

【讨论】:

    【解决方案2】:

    你试过了吗

    clean_df.to_csv(folder_to_export_path+'/filename.csv')
    

    或者如果使用 python 3.6+

    clean_df.to_csv(f'{folder_to_export_path}/filename.csv')
    

    【讨论】:

    • 我尝试了以下错误:OSError: [Errno 22] Invalid argument: '20.9.6.11:8066/file_info/products/processed_file/filename.csv'
    • @KRAJA 您的代码是在运行它的同一台服务器上编写的吗?
    • 是的,它在同一台服务器上。
    • @KRAJA 然后去掉url部分,你可以像clean_df.to_csv("file_info/products/processed_file/filename.csv")一样直接写入路径
    • 我试过你的方法 FileNotFoundError: [Errno 2] No such file or directory: 这个错误来了。但是当我尝试 clean_df.to_csv("path_to_export") csv 文件已导出到我的工作目录中,名称为 "path_to_export"
    【解决方案3】:

    您的最后一行有语法错误,请尝试使用以下内容进行更正:

    clean_df.to_csv(folder_to_export_path+'/filename.csv')
    

    【讨论】:

    【解决方案4】:

    首先,对于to_csv,您需要传递文件路径(或文件对象)。 所以你的folder_to_export_path='http://20.9.6.11:8066/file_info/products/processed_file' 无效。

    应该是 folder_to_export_path = 'file_info/products/processed_file/filename.csv' 假设您要在 file_info/products/processed_file 目录中导出 CSV。

    其次,to_csv 可以创建一个名为 filename.csv 的文件,如果它不存在但它是 cannot create directories

    如果目录不存在则创建目录,然后保存文件,您可以这样做:

    import os
    import pandas as pd
    
    folder_to_export_path = 'file_info/products/processed_file/'
    if not os.path.exists(folder_to_export_path):
        os.makedirs(folder_to_export_path)
    
    pd.to_csv(os.path.join(folder_to_export_path, 'filename.csv'))
    

    应该可以的。

    【讨论】:

    • 我试过你的方式,当我从本地运行我的代码时,它在我的工作目录中创建了文件夹,该文件夹位于其他地方。为什么不是我的 folder_to_export_path = '20.9.6.11:8066/file_info/products/processed_file' 因为这是我要导出 df 的实际文件位置。当我从外部服务器点击我的 api 时,它应该访问文件位置。
    • 然后像/home/kraja/file_info/products/processed_file/那样指定目录的绝对路径。
    猜你喜欢
    • 2020-11-11
    • 2023-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-24
    • 2016-05-02
    • 2023-01-18
    相关资源
    最近更新 更多