npm
npm

Reputation: 653

How to save pandas dataframe to a .csv with specific filename?

For example I import csv file as data frame and work on some process on pandas

df = pd.read_csv('./label/101_5603_2019-05-02~2019-05-18.csv')
rest of codes to work on the data

How do I save the result to a new csv file with the names including 8 first character of the original csv files (101_5603.csv)? Thanks!

Upvotes: 0

Views: 254

Answers (1)

jezrael
jezrael

Reputation: 862511

Use:

import os

f = './label/101_5603_2019-05-02~2019-05-18.csv'
url, ext = os.path.splitext(os.path.basename(f))
new = url[:8] + ext
print (new)
101_5603.csv

new = os.path.dirname(f) + '/' + url[:8] + ext
print (new)
./label/101_5603.csv

new = os.path.join(os.path.dirname(f), url[:8] + ext)
print (new)
./label\101_5603.csv

And pass it to DataFrame.to_csv:

df.to_csv(new, index=False)

Upvotes: 3

Related Questions