[英]How can I convert a dataframe to csv and save it to return it?
I'm reading a.xlsx file and converting it to.csv but I need to return it as a.csv because I don't have access to the path where it should be stored.我正在读取 a.xlsx 文件并将其转换为 .csv 但我需要将其作为 a.csv 返回,因为我无法访问应该存储它的路径。 I've only been able to return it as a dataframe.
我只能将它作为 dataframe 退回。 Any help will be really appreciated.
任何帮助将不胜感激。 Thanks.
谢谢。
import pandas as pd
def excel_to_csv(myfile):
print(myfile)
data_xls = pd.read_excel(myfile, index_col=None)
data_xls.to_csv(encoding='utf-8', index=False)
return(data_xls)
myfile = request.FILES['file']
if myfile.name.endswith('.xlsx'):
myfile=excel_to_csv(myfile)
if you just want to read an Excel file and get the same data as csv printed to your screen, the following might be useful.如果您只想读取 Excel 文件并获取与打印到屏幕上的 csv 相同的数据,以下可能有用。
def excel_to_csv(file):
df = pd.read_excel(file)
csv_data = df.to_csv(encoding='utf-8', index=False)
return csv_data
If you really want to save the file I think I would need more information to the systems your are using and what exactly are you trying to accomplish.如果你真的想保存文件,我想我需要更多关于你正在使用的系统的信息,以及你到底想要完成什么。
If you're using Django, just save it into /media/
root, then you can access it via url如果您使用的是 Django,只需将其保存到
/media/
root,然后您可以通过 url 访问它
First you need to know the config of MEDIA_ROOT
& MEDIA_URL
inside your settings.py .首先,您需要了解settings.py中
MEDIA_ROOT
和MEDIA_URL
的配置。
If it's not exist, then you can create one如果它不存在,那么您可以创建一个
[ settings.py ] [设置.py ]
MEDIA_ROOT = os.path.join(BASE_DIR, 'myproject/static')
MEDIA_URL = '/media/'
Then, make sure you're already add the media config into your urls.py然后,确保您已经将媒体配置添加到您的urls.py
from django.conf.urls.static import static
urlpatterns = [
# Project url patterns...
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Since you're mentioned this code myfile = request.FILES['file']
, then I assume you're in views.py .既然你提到了这段代码
myfile = request.FILES['file']
,那么我假设你在views.py中。 Last but not least we need FileSystemStorage API.最后但同样重要的是,我们需要FileSystemStorage API。
There you go你有 go
[ views.py ] [视图.py ]
from django.core.files.storage import FileSystemStorage
def upload(request):
if request.method == "POST":
csv_file = request.FILE['file']
fs = FileSystemStorage()
name = fs.save(csv_file.name, csv_file)
print(f"file_name = {fs.url(name)}"
return render(request, 'somepage.html')
Access the file via url, www.yourhost.com/media/file_name
通过 url 访问文件,
www.yourhost.com/media/file_name
/media/file_name
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.