简体   繁体   中英

Open a .csv after using Dataframe.to_csv Python

Is there a way to open a.csv file right after using Dataframe.to_csv?

Currently, I am using os.startfile to open the.csv file in a folder (search for.csv file and open it) - but I want to open the specific.csv I just created using df.to_csv.

Here is my current code using os.startfile:

dirName3 = r"\\xx\xx\SourceFolder"
fn2 = [f2 for f2 in os.listdir(dirName3)\
    if f2.endswith('.csv') and os.path.isfile(os.path.join(dirName3, f2))][0]
path3 = os.path.join(dirName3, fn2)
open1 = os.startfile(path3)

The above code will open the.csv file I've created but only if it is top of the folder. So if there are others in the folder it may not be at the top and may open a different file.

I also can't specify an absolute path because the.csv name (using df.to_csv) will change day to day based on user input. I also won't be able to search by date because there may be multiple files from the same day in the folder.

Any help appreciated.

Answering my own question after discussion with others in comments above.

Came up with this to solve the problem:

import os

dirName3 = r"\\xx\xx\Source Folder"
fn2 = [f2 for f2 in os.listdir(dirName3)\
    if f2.endswith(str(datetime.now().strftime('%d_%m_%y_')) + Qname1 + '.csv') and os.path.isfile(os.path.join(dirName3, f2))][0]
path3 = os.path.join(dirName3, fn2)
open1 = os.startfile(path3)

Using f.endswith - instead of '.csv' as in my original above, I used the same information I used to write the csv (using to_csv function which isn't included here). This really only works because I have included a date stamp in the file names - because the Qname1 (user input) can be similar for different days I need the date to differentiate between files.

Cheers stackoverflow.

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