简体   繁体   中英

Create file name from variable values in python

I would like to create a.xlsx file using the name of an existing variable. I need to dynamically create the Excel name in df.to_excel for a given stock. For example, create TSLA.xlsx for a data frame.

    ticker = 'TSLA'
    xlfile = ticker + ".xlsx"
    df=pd.read_csv(query_string)
    df.to_excel(xlfile, index=False)

I get Permission denied: 'TSLA.xlsx'

However the following works just fine:

    df=pd.read_csv(query_string) 
    print(df)
    df.to_excel("TSLA.xlsx", index=False)

Thanks for all your help!

As ForceBru said "TSlA.xlsx".= "TSLA.xlsx" and to overcome the permission denied, simply run as root user. sudo python3 yourFile.py

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