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













3












$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









share|improve this question











$endgroup$
















    3












    $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









    share|improve this question











    $endgroup$














      3












      3








      3


      1



      $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









      share|improve this question











      $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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Feb 19 '16 at 6:41









      200_success

      130k17154419




      130k17154419










      asked Feb 19 '16 at 4:29









      pyNovice89pyNovice89

      18115




      18115




















          2 Answers
          2






          active

          oldest

          votes


















          3












          $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





          share|improve this answer











          $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


















          0












          $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)```




          share








          New contributor




          Kabeer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
          Check out our Code of Conduct.






          $endgroup$












            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
            );



            );













            draft saved

            draft discarded


















            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









            3












            $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





            share|improve this answer











            $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















            3












            $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





            share|improve this answer











            $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













            3












            3








            3





            $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





            share|improve this answer











            $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






            share|improve this answer














            share|improve this answer



            share|improve this answer








            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
















            • $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













            0












            $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)```




            share








            New contributor




            Kabeer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
            Check out our Code of Conduct.






            $endgroup$

















              0












              $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)```




              share








              New contributor




              Kabeer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.






              $endgroup$















                0












                0








                0





                $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)```




                share








                New contributor




                Kabeer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.






                $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)```





                share








                New contributor




                Kabeer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.








                share


                share






                New contributor




                Kabeer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.









                answered 5 mins ago









                KabeerKabeer

                1




                1




                New contributor




                Kabeer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.





                New contributor





                Kabeer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.






                Kabeer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                Check out our Code of Conduct.



























                    draft saved

                    draft discarded
















































                    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.




                    draft saved


                    draft discarded














                    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





















































                    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







                    Popular posts from this blog

                    名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

                    Prove that NP is closed under karp reduction?Space(n) not closed under Karp reductions - what about NTime(n)?Class P is closed under rotation?Prove or disprove that $NL$ is closed under polynomial many-one reductions$mathbfNC_2$ is closed under log-space reductionOn Karp reductionwhen can I know if a class (complexity) is closed under reduction (cook/karp)Check if class $PSPACE$ is closed under polyonomially space reductionIs NPSPACE also closed under polynomial-time reduction and under log-space reduction?Prove PSPACE is closed under complement?Prove PSPACE is closed under union?

                    Is my guitar’s action too high? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Strings too stiff on a recently purchased acoustic guitar | Cort AD880CEIs the action of my guitar really high?Μy little finger is too weak to play guitarWith guitar, how long should I give my fingers to strengthen / callous?When playing a fret the guitar sounds mutedPlaying (Barre) chords up the guitar neckI think my guitar strings are wound too tight and I can't play barre chordsF barre chord on an SG guitarHow to find to the right strings of a barre chord by feel?High action on higher fret on my steel acoustic guitar