简体   繁体   中英

Is there a way to automatically add a filename extension when using the pandas df.to_csv?

I know how to use 'defaultextension' and 'filetypes', as follows:

self.filetypes = (('CSV files', '*.csv'), ('CSV files', '*.csv'))
self.result_file = fd.asksaveasfile(filetypes = self.filetypes, defaultextension = 'csv')

I can simply add the extension when entering the filename, but I'd prefer not to do that. If I enter 'result' for my filename, I'd like for the actual filename to be result.csv.

While I'm at it, I know my filetypes specification looks a little odd, two identical options. When reading files, I couldn't figure out how to provide only one option without getting an error message. This seems to work, at least when reading. Not sure if that's part of my problem when writing.

you can use Pathlib.path.suffix attribute from the pathlib library.

assuming you have a file called 'test.csv' in the same directory.

from pathlib import Path 
file = Path('test.csv')
df = pd.read_csv(file)
#do stuff
df.to_csv(f"new_name.{file.suffix}")
print(file.suffix)
'.csv'

I just figured this out myself. Rather than delete the question, I thought it might be better to provide the answer, in case someone else would benefit from it.

I was using the 'asksaveasfile()' function, which actually opens a file for writing, creating it if necessary.

I have discovered that 'asksaveasfilename()' returns the name of a file the user proposes to open, but does not actually open the file. That allows me to easily add whatever extension I like prior to opening the file and writing to it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM