0

I would like to name new CSV files similar to their corresponding xlsx files

import pandas as pd

for filename in my_path.glob('*.xlsx'):

    read_file = pd.read_excel (str(filename)', sheet_name='My Excel sheet name')
    read_file.to_csv ("XLSX NAME SHOULD = CSV NAME.csv', index = None, header=True)
2
  • import os filename_without_extension = os.path.splitext(r'/path/to/some/file.xlsx')[0]) And then use os.path.join() to create whatever you want Commented Jan 23, 2022 at 0:06
  • You have a quote wrongly placed, not sure if it's a typo here on SO or in your real code.: str(filename)' Commented Jan 23, 2022 at 0:11

1 Answer 1

1

To get the filename with path but without extension use os.path.splitext

from os import path 

path = "/path/to/file.txt"
path.splitext(path)
# -> ["/path/to/file", "txt"]

To get the filename without the path :

from os import path 

path = "/path/to/file.txt"
path.basename(path)
# -> "file.txt"

So to change the extension from xlsx to csv :

from os import path 

path = "/path/to/file.xlsx"
filename = path.splitext(path)[0] + '.csv'
# -> "/path/to/file.csv"

And if you need to change the path to save the file in another folder, then you can use basename first.

Sign up to request clarification or add additional context in comments.

3 Comments

I have multiple files that need to be converted not sure if this helps
Then you just need to put this in a loop with for filename in my_path.glob('*.xlsx'):
Thanks, also could you please take look on this stackoverflow.com/questions/70985695/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.