0

I am trying to read all files from a folder to drop unwanted variables and export the files to a different location not to override the existing files. But I get the below error. Any help is much appreciated.

Below is the code I am using:

from pathlib import Path
folder = (r"C:\Users\Mand\Documents")
col_to_delete = ['Col1', 'Col2', 'Col3', 'Col4']


for file in Path(folder).glob('*.xlsx'):
    df = pd.read_excel(file)
    df = df.drop(labels = col_to_delete, axis=1, inplace = True)
    
df.to_excel(file.with_suffix('.xlsx'),index = False)

Below is the error I get:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-33-8a2ee75be42d> in <module>
      8     **df = df.drop(labels = col_to_delete, axis=1, inplace = True)**
      9 
---> 10 df.to_excel(file.with_suffix('.xlsx'),index = False)
     11 

**AttributeError:** 'NoneType' object has no attribute 'to_excel'

ChKYu
  • 25
  • 6
  • remove the `inplace = True` when you assign it back :-> instead of `df = df.drop(labels = col_to_delete, axis=1, inplace = True)` do `df = df.drop(labels = col_to_delete, axis=1)` – anky Mar 19 '21 at 15:33
  • I get a different error when I removed ```inplace = True``` Error: ```KeyError: "['Col1'\n 'Col2'\n 'Col3'\n 'Col4'] not found in axis"``` – ChKYu Mar 19 '21 at 15:36
  • That is a different issue, not related to this question. you can check what `col_to_delete` returns and if you have those columns exactly in `df.columns` – anky Mar 19 '21 at 15:37
  • The columns exist and also when I have used the same columns on single excel file it works but when I am using the above code to loop though multiple files it doesn't work. I have also checked all files the same columns exist in all files. Anyway I will raise a new question for that. Thanks for the help! – ChKYu Mar 19 '21 at 15:52

0 Answers0