Count how many text files in a directory using python 2.7 and edit them -


i need counting amount of files in directory/folder (windows 7) in python if there more 20 .txt files can delete there 20 files .txt. if create one, using python, deletes oldest one.

any answers helpful, thank you.

import os (_, _, my_files) = os.walk("c:\\users\\guest.user\\task2").next() amount = len([f f in my_files if f.endswith('.txt')])  print amount  if amount > 20: #this next problem - needs truncate file once there more 20 

count txt files

import os   (_, _, my_files) = os.walk('some_directory').next() print len([f f in my_files if f.endswith('.txt')]) 

count txt files , delete ones that're beyond first 10

import os   (_, _, my_files) = os.walk('some_directory').next() if len([f f in my_files if f.endswith('.txt')]) > 10:     f in my_files[9:]:         os.remove(os.path.join('some_directory', f)) 

count txt files , delete after x-number of files

import os   my_directory = 'some_directory' max_files = 20  (_, _, my_files) = os.walk(my_directory).next()  if len([f f in my_files if f.endswith('.txt')]) > max_files:     f in my_files[max_files-1:]:         os.remove(os.path.join(my_directory, f)) 

Comments

Popular posts from this blog

Email notification in google apps script -

c++ - Difference between pre and post decrement in recursive function argument -

javascript - IE11 incompatibility with jQuery's 'readonly'? -