0

So i built some dataframe using pandas, and eventually i have to export a .csv file with it.

The code looks like this:

df.to_csv('file_name.csv')

and it completely works. However, i need to place the day's date in front of the file_name for easy access and bookkeeping (this process is gonna be repeated many times). So i wrote something like this

today = '30/06/2021'
df.to_csv( today + 'file_name.csv')

but then it doesn't work, it raises: "FileNotFoundError: [Errno 2] No such file or directory: '30/06/2021 file_name.csv'". I also tried many alternatives such as declaring

file_name = '30/06/2021 file_name.csv'
df.to_csv(file_name)

fstrings, string.format() but none worked.

How can I use a variable string to complement file names in pandas?

The full error reads:

  File "/home/vni/anaconda3/lib/python3.7/site-packages/pandas/core/generic.py", line 3403, in to_csv
    storage_options=storage_options,
  File "/home/vni/anaconda3/lib/python3.7/site-packages/pandas/io/formats/format.py", line 1083, in to_csv
    csv_formatter.save()
  File "/home/vni/anaconda3/lib/python3.7/site-packages/pandas/io/formats/csvs.py", line 234, in save
    storage_options=self.storage_options,
  File "/home/vni/anaconda3/lib/python3.7/site-packages/pandas/io/common.py", line 652, in get_handle
    newline="",
FileNotFoundError: [Errno 2] No such file or directory: '28/06/2021 entregas_saida.csv'

Process finished with exit code 1
Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Vni Versvs
  • 21
  • 5
  • Hey. Vnii - pandas cannot find the file - probably the path is incorrect. – Piotr Żak Jun 30 '21 at 16:10
  • As the error message suggest, you should check if this file actually exists. Or if the path to the file is correct – Gealber Jun 30 '21 at 16:12
  • You have `/` in your filename and that's going to be interpreted as a directory/filepath. Consider using dashes instead so it can write to your file system. If this is a windows systems then you can't use the following characters in your filename: `\/:*?"<>` – JNevill Jun 30 '21 at 16:16
  • Does this answer your question? [What characters are forbidden in Windows and Linux directory names?](https://stackoverflow.com/questions/1976007/what-characters-are-forbidden-in-windows-and-linux-directory-names) –  Jun 30 '21 at 16:21
  • the file does not exist, i want to create it. – Vni Versvs Jun 30 '21 at 19:01
  • @JustinEzequiel it does – Vni Versvs Jun 30 '21 at 19:03

2 Answers2

3

The problem is trying to use / in the file name, using - works fine:

today = '30-06-2021'
df.to_csv( today + 'file_name.csv')
Bruno Carballo
  • 1,156
  • 8
  • 15
1

That looks like 'subfolders', .i.e /30/06/.