Python - Sort files in directory and use latest file in code
python
Solution
`os.listdir` returns the names of files, not full paths to those files. Generally, when you use `os.listdir(SOME_DIR)`, you then need `os.path.join(SOME_DIR, fname)` to get a path you can use to work with the file.
This might work for you:
files = [os.path.join("/", fname) for fname in os.listdir("/")]
latest = max(files, key=os.path.getmtime)
cause = channel.FilePlayer.play(latest)
Problem
Long time reader, first time poster. I am very new to python and I will try to ask my question properly. I have posted a snippet of the .py code I am using below. I am attempting to get the latest modified file in the current directory to be listed and then pass it along later in the code. This is the error I get in my log file when I attempt to run the file: ``` WindowsError: [Error 2] The system cannot find the file specified: '05-30-2012_1500.wav' ``` So it appears that it is in fact pulling a file from the directory, but that's about it. And actually, the file that it pulls up is not the most recently modified file in that directory. ``` latest_page = max(os.listdir("/"), key=os.path.getmtime) cause = channel.FilePlayer.play(latest_page) ```