0

Using Python3 I'm trying to read the newest csv file using pandas in the path and directory specified; but I'm receiving "NotADirectoryError" on "latest_file = os.listdir(latest_date)[-1].

import pandas as pd

import os

#naming path for most recent file
path='/filepath/'

#specifying full path
latest_date = path+os.listdir(path)[-1]+'/'

#identifying newest file in directory
latest_file = os.listdir(latest_date)[-1]
csv_to_read=pd.read_csv(latest_date+latest_file)
display(csv_to_read)
Zach
  • 23
  • 2
  • The easiest thing to do would be to print the result of latest_date+latest_file, and you should see pretty quickly if there's an error in the path to the file. There's probably a missing forward slash – tonneofash Dec 03 '21 at 09:23
  • already checks and there aren't any cases of a missing forward slash – Zach Dec 03 '21 at 17:04

1 Answers1

1

There is no need to do any awkward slicing, see here.

import glob
import os
import pandas as pd

list_of_files = glob.glob('/filepath/*.csv')

To consider the possibility of not having a csv file in the directory:

if list_of_files:
    latest_file = max(list_of_files, key=os.path.getctime)
    csv_to_read = pd.read_csv(latest_file)
saiden
  • 322
  • 3
  • 14
  • that worked, however the file is displaying as blank – Zach Dec 03 '21 at 18:06
  • 1
    That has nothing to with accurately reading the file. If you have troubles you should consider posting a separate issue :). – saiden Dec 03 '21 at 18:30