ulfben

PrintTopNLines

Dec 2nd, 2019
132
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. # Takes a list of directories and prints the top n lines of each .txt file found
  5. # Known bugs:
  6. #   - Files without line breaks won't have their content listed.
  7.  
  8. import sys
  9. import os
  10.  
  11. def getFirstNLines(filename, linesToRead):
  12.   firstLines=""
  13.   try:
  14.     with open(filename,'r') as fileHandle:
  15.         try:
  16.           firstLines = [next(fileHandle) for x in range(linesToRead)]
  17.         except StopIteration:
  18.           pass #not enough lines in the file. Ignore and move on.
  19.   except IOError:
  20.     print("Unable to read file: " + filename)
  21.   return firstLines
  22.  
  23. def getFilesInDir(path, ext):
  24.   files = []
  25.   for file in os.listdir(path):
  26.     if file.endswith(ext):
  27.         files.append(path+file)
  28.   return files
  29.  
  30. def getFilesInDirectories(paths, extension):
  31.     files = []
  32.     for dir in paths:
  33.         try:
  34.             files.extend(getFilesInDir(dir, extension));
  35.         except IOError:
  36.             print("Unable to read path: " + dir)
  37.         except OSError:
  38.             print("No such file or directory: " + dir)
  39.     return files
  40.  
  41. def prettyPrint(filePath, content):
  42.   title = os.path.basename(filePath) #print only filename. might be a misstake -  user probably wants to  know where the file was located too?
  43.   print(title + ":")
  44.   for line in content:
  45.     print("\t" + line.rstrip()); #rstrip to rid of trailing newlines
  46.  
  47. def main():
  48.   if len(sys.argv) == 1: #1st argument is always the script name
  49.     print("Not enough arguments provided")
  50.     return
  51.   FILE_EXT = ".txt"
  52.   LINES_TO_READ = 2
  53.   files = getFilesInDirectories(sys.argv[1:], FILE_EXT)  #slice the array to ignore 1st argument
  54.   for filePath in files:
  55.     prettyPrint(filePath, getFirstNLines(filePath, LINES_TO_READ))
  56.  
  57. if __name__ == "__main__":
  58.     main()
RAW Paste Data

Adblocker detected! Please consider disabling it...

We've detected AdBlock Plus or some other adblocking software preventing Pastebin.com from fully loading.

We don't have any obnoxious sound, or popup ads, we actively block these annoying types of ads!

Please add Pastebin.com to your ad blocker whitelist or disable your adblocking software.

×