Print data from os.listdir() using pandas

Viewed 390

I'm having trouble pulling data from a folder that contains two csv files that is updated to replace the older of the two files every day. Because I always want to pull the last/-1/most recent file that is in that folder, what query can I run to pull the newest file using pandas in Python 3 on JupyterLab? When I print the data that I want to pull I receive None as a response.

Python3 Code in JupyterLab:

#install prep
%conda install pandas
import pandas as pd

#install 
import glob

#naming path for most recent file
FolderPath="Pathname of folder containing the two most recent csv files"

import os

#display name of most recent file in the pathname folder aka FolderPath
NewestData = os.listdir(FolderPath)
print(NewestData[-1])

#pull data from 'NewestData'
UpdatedData = pd.read(NewestData[-1])

print(UpdatedData)
1 Answers

If you can guarantee that the file listed is indeed a file and not a folder, this should work.

FolderPath="C:/testpath"
NewestData = os.listdir(FolderPath)
UpdatedData = pd.read(os.path.join(FolderPath, NewestData[-1]))

The only difference is that you are not adding the FolderPath prefix to your listed directories, because OS does not do that automatically.

Related