My code which is aimed at showing the last opened file, outputs always one special file even though it is not the last opened file. Also my code doesn't work if it isn't in the same folder as the data I am searching for.
I'm a complete newbie in python and this is actually the first program I've ever created with it. I wanted to make my life easier and make a little terminal application which should automatically debug my code. My first step was to create a code that shows the last opened project because if the folder i want to put my projects in is full it would be hard to search the name of my project. So I've come up with this:
import os
z = 3
o = r"/home/myname/Dokumente/Python"
list = os.listdir(o)
list_length = len(list)
list_time = []
list_low = []
print(list)
while list_length != 0:
list_length -= 1
print((os.path.getatime(list[list_length-1])))
list_time.append((os.path.getatime(list[list_length-1])))
print(list_time)
else:
list_time.reverse()
recent = list_time.index(min(list_time))
print(recent)
print("recently opened")
print(list[recent])
print(list)
To my second problem (not working when not in the same folder) this is the output of the Terminal:
['Hello_World.py', 'Python_Debugger_Kopie.py']
Traceback (most recent call last):
File "Python_Debugger.py", line 14, in <module>
print((os.path.getatime(list[list_length-1])))
File "/usr/lib/python3.7/genericpath.py", line 60, in getatime
return os.stat(filename).st_atime
FileNotFoundError: [Errno 2] No such file or directory: 'Hello_World.py'
You have a path problem I think.
os.path.getatime(file)
Returns the time of last access of file. So when you call :
os.path.getatime(list[list_length-1])
Python is trying to find the file 'Hello_World.py'
.
However, this file is in your "/home/myname/Dokumente/Python"
directory.
So I think you could write this at the beggining of your file :
path_dir = '/home/myname/Dokumente/Python'
os.chdir(path_dir)
It will change your current working directory, and it should work.