PDA

View Full Version : [SOLVED] PYTHON: how to find the newest file in a directory and open it with cat



leahk
July 7th, 2010, 07:06 PM
i am trying to first identify the last file added to the directory and then open it with cat.


r=commands.getoutput('ls -ct1 | head -1')

print r

os.system('cat r')



if i wrote os.system(cat 'name of file') it works but not with the variable

??

xb12x
July 7th, 2010, 07:20 PM
Keep in mind that I'm currently learning Python myself:

c = 'cat'
x = c + ' ' + r
os.system(x)

schauerlich
July 7th, 2010, 08:17 PM
os.system is evil.


filelist = os.listdir(os.getcwd())
filelist = filter(lambda x: not os.path.isdir(x), filelist)
newest = max(filelist, key=lambda x: os.stat(x).st_mtime)

"newest" will be a string with the name of the last modified file. You can then open it just like you would anything else.

leahk
July 7th, 2010, 08:42 PM
the code is printing out the .pyc file....not the.py??

schauerlich
July 7th, 2010, 08:45 PM
the code is printing out the .pyc file....not the.py??

Well, the .pyc file is created when the .py file is run, so it's going to be newer. You can manually filter out specific file extensions. Look into the "endswith" method of the string class, and look at the line using "filter".

geirha
July 8th, 2010, 10:15 AM
And then, instead of running os.system('cat...'), do the "cat" with python.

schauerlich
July 9th, 2010, 01:54 AM
do the "cat" with python.

http://grab.by/grabs/a921b5c18ce82835b213355fcd69b8d0.png

Am I doing it right?

geirha
July 9th, 2010, 09:24 AM
http://grab.by/grabs/a921b5c18ce82835b213355fcd69b8d0.png

Am I doing it right?

Yes, that's exactly what I meant :)