Pragyaditya Das
Pragyaditya Das

Reputation: 1696

Save an excel file as data frame after input()

I want to take the file path input from the user, and then do manipulations on the file using pandas.

As of now, I do the following,

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+') 

I am assuming (I guess, I am going wrong here), that the file is getting saved temporarily in f.

After which I do the following,

xl = pd.ExcelFile(f)

Which does not work.

The error that is get is,

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>

Can someone help me?

Regards.

Upvotes: 0

Views: 187

Answers (1)

el_Rinaldo
el_Rinaldo

Reputation: 1018

First you need to save your input as pandas DataFrame and then save it in excel format. I guess the format of the input file is excel as well. I would do the following:

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)

You can now just run df to see the data frame.

For saving, please, take a look at this documentation: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.to_excel.html

Upvotes: 1

Related Questions