аватар question@mail.ru · 01.01.1970 03:00

Selection of the last by the date of the file from the catalog

I study python , trying to write a script that takes a file that was created from a certain folder that was created late others. How to do this?

аватар answer@mail.ru · 01.01.1970 03:00

Let some way be set:

  path =  r'c: \ python27 '   

you need to get a list of files along this path:

   import  osfiles = os.listdir (Path)   

on this The stage is advisable to check that the file list is not empty. We make just if films: , and everything that is scheduled below is going inside the IF block.

We simply tu the file list into the list of files with ways:

  philes = "" [OS.Path.JOIN (Path, File)  for  file  in  files]     

the function os.path.join () "attaches" the path to the file name. Depending on the system, this feature inserts either a straight slash, or a reverse, or nothing at all, if the slash is already at the end of the jouey.

We leave only files in the list:

  Files = [File  for  file  in  files  if  os.path.ospile]     

the functions of the file will determine the function os.path.getctime () . You need to find a file that has a maximum modification date. To do this, we will use the max function with an additional key parameter, which allows you to set a function that will be applied to each object from the list, the minimum will be determined by the corresponding retu values:

   & gt; & gt; & gt;   max  (files, key = os.path.getctime)   'C: \\ python27 \\ liceense.txt'    

in other other in the other I see the answers sort or sorted . Why not apply it? It's simple: why sort the list (possibly large), when you need to only go along it once and find the maximum.

Latest

Similar