Finding the latest file in a folderByte by byte directory comparison ignoring folder structures and file name differencesGlob-Like Search in VBAMP3 Vote Collator - FinalFolder watching in GoFinding all non-empty directories and their files on an SFTP server with ParamikoRecursively search a folder for photosFile / Folder Tally ToolApostle Galaxies: dict subclass with disk cachingFinding and deleting duplicate files in a folderGitHub repo tree generator
Do we have to expect a queue for the shuttle from Watford Junction to Harry Potter Studio?
How to convince somebody that he is fit for something else, but not this job?
Does Doodling or Improvising on the Piano Have Any Benefits?
Change the color of a single dot in `ddot` symbol
Why do ¬, ∀ and ∃ have the same precedence?
Review your own paper in Mathematics
How do you make your own symbol when Detexify fails?
The IT department bottlenecks progress, how should I handle this?
Making grids in QGIS
Why is it that I can sometimes guess the next note?
Is there a way to have vectors outlined in a Vector Plot?
Why should universal income be universal?
Which was the first story featuring espers?
Can a stoichiometric mixture of oxygen and methane exist as a liquid at standard pressure and some (low) temperature?
Does the Linux kernel need a file system to run?
How to draw a matrix with arrows in limited space
Giving feedback to someone without sounding prejudiced
Non-trope happy ending?
What's the name of the logical fallacy where a debater extends a statement far beyond the original statement to make it true?
Is this part of the description of the Archfey warlock's Misty Escape feature redundant?
How would you translate "more" for use as an interface button?
Can I cause damage to electrical appliances by unplugging them when they are turned on?
What is the difference between lands and mana?
What fields between the rationals and the reals allow a good notion of 2D distance?
Finding the latest file in a folder
Byte by byte directory comparison ignoring folder structures and file name differencesGlob-Like Search in VBAMP3 Vote Collator - FinalFolder watching in GoFinding all non-empty directories and their files on an SFTP server with ParamikoRecursively search a folder for photosFile / Folder Tally ToolApostle Galaxies: dict subclass with disk cachingFinding and deleting duplicate files in a folderGitHub repo tree generator
$begingroup$
I'm a bit new to Python and sort of learning on my own. I wrote a small function to help me find the latest file in a directory. Taking a step back, it reads a bit janky and I was curious what steps or what resources I could look into to help me make this more friendly. Should I be returning False
? Or 0
?
Inside my example/files directory are 3 files which were, for this example, created on the dates specified in the file name:
example/files/randomtext011.201602012.txt
example/files/randomtext011.201602011.txt
example/files/randomtext011.201602013.txt
import os.path
import glob
import datetime
dir = 'example/files'
file_pattern = 'randomtext011.*.txt'
def get_latest_file(file_pattern,path=None):
if path is None:
list_of_files = glob.glob('0'.format(file_pattern))
if len(list_of_files)> 0:
return os.path.split(max(list_of_files, key = os.path.getctime))[1]
else:
list_of_files = glob.glob('0/1'.format(path, file_pattern))
if len(list_of_files) > 0:
return os.path.split(max(list_of_files,key=os.path.getctime))[1]
return False
python file-system
$endgroup$
add a comment |
$begingroup$
I'm a bit new to Python and sort of learning on my own. I wrote a small function to help me find the latest file in a directory. Taking a step back, it reads a bit janky and I was curious what steps or what resources I could look into to help me make this more friendly. Should I be returning False
? Or 0
?
Inside my example/files directory are 3 files which were, for this example, created on the dates specified in the file name:
example/files/randomtext011.201602012.txt
example/files/randomtext011.201602011.txt
example/files/randomtext011.201602013.txt
import os.path
import glob
import datetime
dir = 'example/files'
file_pattern = 'randomtext011.*.txt'
def get_latest_file(file_pattern,path=None):
if path is None:
list_of_files = glob.glob('0'.format(file_pattern))
if len(list_of_files)> 0:
return os.path.split(max(list_of_files, key = os.path.getctime))[1]
else:
list_of_files = glob.glob('0/1'.format(path, file_pattern))
if len(list_of_files) > 0:
return os.path.split(max(list_of_files,key=os.path.getctime))[1]
return False
python file-system
$endgroup$
add a comment |
$begingroup$
I'm a bit new to Python and sort of learning on my own. I wrote a small function to help me find the latest file in a directory. Taking a step back, it reads a bit janky and I was curious what steps or what resources I could look into to help me make this more friendly. Should I be returning False
? Or 0
?
Inside my example/files directory are 3 files which were, for this example, created on the dates specified in the file name:
example/files/randomtext011.201602012.txt
example/files/randomtext011.201602011.txt
example/files/randomtext011.201602013.txt
import os.path
import glob
import datetime
dir = 'example/files'
file_pattern = 'randomtext011.*.txt'
def get_latest_file(file_pattern,path=None):
if path is None:
list_of_files = glob.glob('0'.format(file_pattern))
if len(list_of_files)> 0:
return os.path.split(max(list_of_files, key = os.path.getctime))[1]
else:
list_of_files = glob.glob('0/1'.format(path, file_pattern))
if len(list_of_files) > 0:
return os.path.split(max(list_of_files,key=os.path.getctime))[1]
return False
python file-system
$endgroup$
I'm a bit new to Python and sort of learning on my own. I wrote a small function to help me find the latest file in a directory. Taking a step back, it reads a bit janky and I was curious what steps or what resources I could look into to help me make this more friendly. Should I be returning False
? Or 0
?
Inside my example/files directory are 3 files which were, for this example, created on the dates specified in the file name:
example/files/randomtext011.201602012.txt
example/files/randomtext011.201602011.txt
example/files/randomtext011.201602013.txt
import os.path
import glob
import datetime
dir = 'example/files'
file_pattern = 'randomtext011.*.txt'
def get_latest_file(file_pattern,path=None):
if path is None:
list_of_files = glob.glob('0'.format(file_pattern))
if len(list_of_files)> 0:
return os.path.split(max(list_of_files, key = os.path.getctime))[1]
else:
list_of_files = glob.glob('0/1'.format(path, file_pattern))
if len(list_of_files) > 0:
return os.path.split(max(list_of_files,key=os.path.getctime))[1]
return False
python file-system
python file-system
edited Feb 19 '16 at 6:41
200_success
130k17154419
130k17154419
asked Feb 19 '16 at 4:29
pyNovice89pyNovice89
18115
18115
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
$begingroup$
First of all, I think that your variable names are quite good.
Should I be returning False? Or 0?
I would recommend None
Don't repeat yourself
As you can see, the two branches of your if
else
are very similar.
Instead you could do a
if path is None:
fullpath = file_pattern
else:
fullpath = path + '/' + file_pattern
But joining paths like this is not very pythonic (and might cause problems on windows).
Instead, fullpath = os.path.join(path, file_pattern)
is what you are looking for.
About the arguments
You can take inspiration of the os.path.join even further and change the order of your arguments (and completely remove the branching):
def get_latest_file(path, *paths):
fullpath = os.path.join(path, paths)
...
get_latest_file('example', 'files','randomtext011.*.txt')
Use docstrings
And then you might think that the way to call it is not trivial and want to document it: let's use a docstring !
def get_latest_file(path, *paths):
"""Returns the name of the latest (most recent) file
of the joined path(s)"""
fullpath = os.path.join(path, *paths)
Miscellaneous
If you use Python 3, you can use iglob instead.
For the os.path.split
, I prefer using it like this (instead of the 1
index):
folder, filename = os.path.split(latest_file)
The import datetime
is not used.
Instead of if len(list_of_files)> 0:
, you can simply do if list_of_files:
Revised code
def get_latest_file(path, *paths):
"""Returns the name of the latest (most recent) file
of the joined path(s)"""
fullpath = os.path.join(path, *paths)
list_of_files = glob.glob(fullpath) # You may use iglob in Python3
if not list_of_files: # I prefer using the negation
return None # because it behaves like a shortcut
latest_file = max(list_of_files, key=os.path.getctime)
_, filename = os.path.split(latest_file)
return filename
$endgroup$
$begingroup$
Thanks oliverpool! Your response is really helpful and definitely gives me a number of next steps to look into.
$endgroup$
– pyNovice89
Feb 19 '16 at 15:52
add a comment |
$begingroup$
Consider you has the directories in a particular path, then we need the simple code like as shown in below.
files = os.listdir(path)
latest_file = files[0]
for key in files:
if os.path.getctime(path+key) > os.path.getctime(path + latest_file):
latest = key
print(latest)```
New contributor
$endgroup$
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
return StackExchange.using("mathjaxEditing", function ()
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
);
);
, "mathjax-editing");
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f120494%2ffinding-the-latest-file-in-a-folder%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
$begingroup$
First of all, I think that your variable names are quite good.
Should I be returning False? Or 0?
I would recommend None
Don't repeat yourself
As you can see, the two branches of your if
else
are very similar.
Instead you could do a
if path is None:
fullpath = file_pattern
else:
fullpath = path + '/' + file_pattern
But joining paths like this is not very pythonic (and might cause problems on windows).
Instead, fullpath = os.path.join(path, file_pattern)
is what you are looking for.
About the arguments
You can take inspiration of the os.path.join even further and change the order of your arguments (and completely remove the branching):
def get_latest_file(path, *paths):
fullpath = os.path.join(path, paths)
...
get_latest_file('example', 'files','randomtext011.*.txt')
Use docstrings
And then you might think that the way to call it is not trivial and want to document it: let's use a docstring !
def get_latest_file(path, *paths):
"""Returns the name of the latest (most recent) file
of the joined path(s)"""
fullpath = os.path.join(path, *paths)
Miscellaneous
If you use Python 3, you can use iglob instead.
For the os.path.split
, I prefer using it like this (instead of the 1
index):
folder, filename = os.path.split(latest_file)
The import datetime
is not used.
Instead of if len(list_of_files)> 0:
, you can simply do if list_of_files:
Revised code
def get_latest_file(path, *paths):
"""Returns the name of the latest (most recent) file
of the joined path(s)"""
fullpath = os.path.join(path, *paths)
list_of_files = glob.glob(fullpath) # You may use iglob in Python3
if not list_of_files: # I prefer using the negation
return None # because it behaves like a shortcut
latest_file = max(list_of_files, key=os.path.getctime)
_, filename = os.path.split(latest_file)
return filename
$endgroup$
$begingroup$
Thanks oliverpool! Your response is really helpful and definitely gives me a number of next steps to look into.
$endgroup$
– pyNovice89
Feb 19 '16 at 15:52
add a comment |
$begingroup$
First of all, I think that your variable names are quite good.
Should I be returning False? Or 0?
I would recommend None
Don't repeat yourself
As you can see, the two branches of your if
else
are very similar.
Instead you could do a
if path is None:
fullpath = file_pattern
else:
fullpath = path + '/' + file_pattern
But joining paths like this is not very pythonic (and might cause problems on windows).
Instead, fullpath = os.path.join(path, file_pattern)
is what you are looking for.
About the arguments
You can take inspiration of the os.path.join even further and change the order of your arguments (and completely remove the branching):
def get_latest_file(path, *paths):
fullpath = os.path.join(path, paths)
...
get_latest_file('example', 'files','randomtext011.*.txt')
Use docstrings
And then you might think that the way to call it is not trivial and want to document it: let's use a docstring !
def get_latest_file(path, *paths):
"""Returns the name of the latest (most recent) file
of the joined path(s)"""
fullpath = os.path.join(path, *paths)
Miscellaneous
If you use Python 3, you can use iglob instead.
For the os.path.split
, I prefer using it like this (instead of the 1
index):
folder, filename = os.path.split(latest_file)
The import datetime
is not used.
Instead of if len(list_of_files)> 0:
, you can simply do if list_of_files:
Revised code
def get_latest_file(path, *paths):
"""Returns the name of the latest (most recent) file
of the joined path(s)"""
fullpath = os.path.join(path, *paths)
list_of_files = glob.glob(fullpath) # You may use iglob in Python3
if not list_of_files: # I prefer using the negation
return None # because it behaves like a shortcut
latest_file = max(list_of_files, key=os.path.getctime)
_, filename = os.path.split(latest_file)
return filename
$endgroup$
$begingroup$
Thanks oliverpool! Your response is really helpful and definitely gives me a number of next steps to look into.
$endgroup$
– pyNovice89
Feb 19 '16 at 15:52
add a comment |
$begingroup$
First of all, I think that your variable names are quite good.
Should I be returning False? Or 0?
I would recommend None
Don't repeat yourself
As you can see, the two branches of your if
else
are very similar.
Instead you could do a
if path is None:
fullpath = file_pattern
else:
fullpath = path + '/' + file_pattern
But joining paths like this is not very pythonic (and might cause problems on windows).
Instead, fullpath = os.path.join(path, file_pattern)
is what you are looking for.
About the arguments
You can take inspiration of the os.path.join even further and change the order of your arguments (and completely remove the branching):
def get_latest_file(path, *paths):
fullpath = os.path.join(path, paths)
...
get_latest_file('example', 'files','randomtext011.*.txt')
Use docstrings
And then you might think that the way to call it is not trivial and want to document it: let's use a docstring !
def get_latest_file(path, *paths):
"""Returns the name of the latest (most recent) file
of the joined path(s)"""
fullpath = os.path.join(path, *paths)
Miscellaneous
If you use Python 3, you can use iglob instead.
For the os.path.split
, I prefer using it like this (instead of the 1
index):
folder, filename = os.path.split(latest_file)
The import datetime
is not used.
Instead of if len(list_of_files)> 0:
, you can simply do if list_of_files:
Revised code
def get_latest_file(path, *paths):
"""Returns the name of the latest (most recent) file
of the joined path(s)"""
fullpath = os.path.join(path, *paths)
list_of_files = glob.glob(fullpath) # You may use iglob in Python3
if not list_of_files: # I prefer using the negation
return None # because it behaves like a shortcut
latest_file = max(list_of_files, key=os.path.getctime)
_, filename = os.path.split(latest_file)
return filename
$endgroup$
First of all, I think that your variable names are quite good.
Should I be returning False? Or 0?
I would recommend None
Don't repeat yourself
As you can see, the two branches of your if
else
are very similar.
Instead you could do a
if path is None:
fullpath = file_pattern
else:
fullpath = path + '/' + file_pattern
But joining paths like this is not very pythonic (and might cause problems on windows).
Instead, fullpath = os.path.join(path, file_pattern)
is what you are looking for.
About the arguments
You can take inspiration of the os.path.join even further and change the order of your arguments (and completely remove the branching):
def get_latest_file(path, *paths):
fullpath = os.path.join(path, paths)
...
get_latest_file('example', 'files','randomtext011.*.txt')
Use docstrings
And then you might think that the way to call it is not trivial and want to document it: let's use a docstring !
def get_latest_file(path, *paths):
"""Returns the name of the latest (most recent) file
of the joined path(s)"""
fullpath = os.path.join(path, *paths)
Miscellaneous
If you use Python 3, you can use iglob instead.
For the os.path.split
, I prefer using it like this (instead of the 1
index):
folder, filename = os.path.split(latest_file)
The import datetime
is not used.
Instead of if len(list_of_files)> 0:
, you can simply do if list_of_files:
Revised code
def get_latest_file(path, *paths):
"""Returns the name of the latest (most recent) file
of the joined path(s)"""
fullpath = os.path.join(path, *paths)
list_of_files = glob.glob(fullpath) # You may use iglob in Python3
if not list_of_files: # I prefer using the negation
return None # because it behaves like a shortcut
latest_file = max(list_of_files, key=os.path.getctime)
_, filename = os.path.split(latest_file)
return filename
edited Feb 19 '16 at 12:45
answered Feb 19 '16 at 7:55
oliverpoololiverpool
1,592425
1,592425
$begingroup$
Thanks oliverpool! Your response is really helpful and definitely gives me a number of next steps to look into.
$endgroup$
– pyNovice89
Feb 19 '16 at 15:52
add a comment |
$begingroup$
Thanks oliverpool! Your response is really helpful and definitely gives me a number of next steps to look into.
$endgroup$
– pyNovice89
Feb 19 '16 at 15:52
$begingroup$
Thanks oliverpool! Your response is really helpful and definitely gives me a number of next steps to look into.
$endgroup$
– pyNovice89
Feb 19 '16 at 15:52
$begingroup$
Thanks oliverpool! Your response is really helpful and definitely gives me a number of next steps to look into.
$endgroup$
– pyNovice89
Feb 19 '16 at 15:52
add a comment |
$begingroup$
Consider you has the directories in a particular path, then we need the simple code like as shown in below.
files = os.listdir(path)
latest_file = files[0]
for key in files:
if os.path.getctime(path+key) > os.path.getctime(path + latest_file):
latest = key
print(latest)```
New contributor
$endgroup$
add a comment |
$begingroup$
Consider you has the directories in a particular path, then we need the simple code like as shown in below.
files = os.listdir(path)
latest_file = files[0]
for key in files:
if os.path.getctime(path+key) > os.path.getctime(path + latest_file):
latest = key
print(latest)```
New contributor
$endgroup$
add a comment |
$begingroup$
Consider you has the directories in a particular path, then we need the simple code like as shown in below.
files = os.listdir(path)
latest_file = files[0]
for key in files:
if os.path.getctime(path+key) > os.path.getctime(path + latest_file):
latest = key
print(latest)```
New contributor
$endgroup$
Consider you has the directories in a particular path, then we need the simple code like as shown in below.
files = os.listdir(path)
latest_file = files[0]
for key in files:
if os.path.getctime(path+key) > os.path.getctime(path + latest_file):
latest = key
print(latest)```
New contributor
New contributor
answered 5 mins ago
KabeerKabeer
1
1
New contributor
New contributor
add a comment |
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f120494%2ffinding-the-latest-file-in-a-folder%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown