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

时间:2018-05-23 07:57:11

标签: python excel pandas

我想从用户那里获取文件路径输入,然后使用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>

有人可以帮助我吗?

问候。

1 个答案:

答案 0 :(得分:1)

首先,您需要将输入保存为pandas DataFrame,然后以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