Home > Enterprise >  Python how to concatenate file names
Python how to concatenate file names

Time:10-10

I'd like to include the month and year in my file name based on the month submitted.

I defined a variable that would be used to insert my file name.

    MTH = '20'   df['Month'].astype(str)   '/01'
    MONTH = pd.to_datetime(MTH).dt.month
    YEAR =  pd.to_datetime(MTH).dt.year

SAVE File Directory:

   df.to_excel(r'C:\OUTPUT\SALES_'  MONTH   '_'   YEAR   '.xlsx', index=False )

Error:

  File "C:\SR\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pandas\core\generic.py", line 2284, in to_excel
    formatter.write(
  File "C:\SR\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pandas\io\formats\excel.py", line 834, in write
    writer = ExcelWriter(  # type: ignore[abstract]
  File "C:\SR\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pandas\io\excel\_xlsxwriter.py", line 191, in __init__
    super().__init__(
  File "C:\SR\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pandas\io\excel\_base.py", line 925, in __init__
    self.handles = get_handle(
  File "C:\SR\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pandas\io\common.py", 
line 608, in get_handle
    ioargs = _get_filepath_or_buffer(
  File "C:\SR\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pandas\io\common.py", 
line 395, in _get_filepath_or_buffer
    raise ValueError(msg)
ValueError: Invalid file path or buffer object type: <class 'pandas.core.series.Series'>
PS C:\SR\Desktop\Python> 

CodePudding user response:

You probably mean:

df.to_excel(r'C:\OUTPUT\SALES_'  MONTH.item()   '_'   YEAR.item()   '.xlsx', index=False )

Or:

df.to_excel(r'C:\OUTPUT\SALES_'  MONTH[0]   '_'   YEAR[0]   '.xlsx', index=False )
  • Related