0

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!

Underoos
  • 4,708
  • 8
  • 42
  • 85
npm
  • 643
  • 5
  • 17
  • Possible duplicate of [Writing a pandas DataFrame to CSV file](https://stackoverflow.com/questions/16923281/writing-a-pandas-dataframe-to-csv-file) – Underoos Aug 05 '19 at 09:57

1 Answers1

3

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)
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252