0

I'm writing a script to import a csv using pandas, then upload it to a SQL server. It all works when I have a test file with one name, but that won't be the case in production. I need to figure out how to import with only a semi-known filename (the filename will always follow the same convention, but there will be differences in the filenames such as dates/times). I should, however, note that there will only ever be one csv file in the folder it's checking. I have tried the wildcard in the import path, but that didn't work.

After it's imported, I also then need to return the filename.

Thanks!

hale6
  • 1
  • 2
  • 2
    To clarify, would this be an accurate re-statement of your question: "Given a directory name, find the name of the only CSV file in it"? If so, `glob.glob(os.path.join(dir, "*.csv"))[0]` or `pathlib.Path(dir).glob("*.csv")[0]` should do that. – Amadan Jul 19 '21 at 16:53
  • That looks like it'd probably work. I'll try that out! – hale6 Jul 19 '21 at 16:57
  • Update, it did indeed work. Thanks! – hale6 Jul 19 '21 at 17:03
  • Does this answer your question? [Find all files in a directory with extension .txt in Python](https://stackoverflow.com/questions/3964681/find-all-files-in-a-directory-with-extension-txt-in-python) – Henry Ecker Jul 19 '21 at 17:16

1 Answers1

0

Look into the OS module:

import os
files = os.listdir("./")
csv_files = [filename for filename in files if filename.endswith(".csv")]

csv_files is a list with all the files that ends with .csv

Henrik Bo
  • 433
  • 2
  • 6