输入后将excel文件另存为数据框()

2024-04-20 03:23:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从用户那里获取文件路径输入,然后使用pandas对文件进行操作。你知道吗

到目前为止,我做了以下工作

import sys
import os
import pandas as pd

user_input = input("Enter the path of your file: ")

assert os.path.exists(user_input), "I did not find the file at, "+str(user_input)
f = open(user_input,'r+') 

我假设文件被临时保存在f中。你知道吗

在那之后我做了以下事情

xl = pd.ExcelFile(f)

这是行不通的。你知道吗

错误是

Enter the path of your file: C:/Users/MyPC/Desktop/Files/Data/11.05.2018/data.xls
---------------------------------------------------------------------------
UnicodeDecodeError                        Traceback (most recent call last)
<ipython-input-6-9bfb9b9b2c74> in <module>()
      7 assert os.path.exists(user_input), "I did not find the file at, "+str(user_input)
      8 f = open(user_input,'r+')
----> 9 xl = pd.ExcelFile(f)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\io\excel.py in __init__(self, io, **kwds)
    289         elif not isinstance(io, xlrd.Book) and hasattr(io, "read"):
    290             # N.B. xlrd.Book has a read attribute too
--> 291             data = io.read()
    292             self.book = xlrd.open_workbook(file_contents=data)
    293         elif isinstance(self._io, compat.string_types):

~\AppData\Local\Continuum\anaconda3\lib\encodings\cp1252.py in decode(self, input, final)
     21 class IncrementalDecoder(codecs.IncrementalDecoder):
     22     def decode(self, input, final=False):
---> 23         return codecs.charmap_decode(input,self.errors,decoding_table)[0]
     24 
     25 class StreamWriter(Codec,codecs.StreamWriter):

UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 545: character maps to <undefined>

有人能帮我吗?你知道吗

敬礼。你知道吗


Tags: 文件thepathinioimportselfpandas
1条回答
网友
1楼 · 发布于 2024-04-20 03:23:17

首先,您需要将输入保存为DataFrame,然后将其保存为excel格式。我猜输入文件的格式也是excel。我会做以下工作:

import sys
import os
import pandas as pd

user_input = input("Enter the path of your file: ")

assert os.path.exists(user_input), "I did not find the file at, "+str(user_input)

df = pd.read_excel(user_input)

现在可以运行df来查看数据帧。你知道吗

为了保存,请查看以下文档:https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html

相关问题 更多 >