News for hackers. Stuff that matters.
Re:Ask HN: Tools you have made for yourself? by mikub on Saturday June 12, 2021 @12:50PM (#27485672)
I am currently learning SQL/Python, I often just wanted to know the headers and how many rows are in a CSV file, so I just wrote a small Python script for it.

  import csv
  import readline

  readline.set_completer_delims(' \t\n=')
  readline.parse_and_bind("tab: complete")

  def csvOpen(file):

      with open(file, "r", newline='', encoding='utf-8-sig')  as csvfile:
          reader = csv.reader(csvfile)
          i = next(reader)
          dRows = sum(1 for line in reader)
          print(f"You have {dRows} rows in the CSV file:\n" f"Your headers are:\n {i}")

  file = input("Please enter the filename to show the CSV   headers: ")

  csvOpen(file)
I also have an alias for it in my .bash_aliases.

  alias sqhead='python /home/user/Coding/Py-Code/sqlHead.py'
Re:Ask HN: Tools you have made for yourself? by roveo on Saturday June 12, 2021 @07:49PM (#27488448)
Nice! It could probably benefit from passing the file as an argument:

  import sys

  file = sys.argv[1]
instead of call to input()

You could probably do:

  if len(sys.argv) > 1:
      file = sys.argv[1]
  else:
      file = input(...)
Re:Ask HN: Tools you have made for yourself? by mikub on Sunday June 13, 2021 @12:31AM (#27489757)
Oh wow, that's a nice improvement. Thank you.
Re:Ask HN: Tools you have made for yourself? by Madeindjs on Saturday June 12, 2021 @05:18PM (#27487504)
This can be done using two lines of Bash

- `head -n 1 <file>` to get headers - `wc -l <file>` to count number of rows

Re:Ask HN: Tools you have made for yourself? by mikub on Sunday June 13, 2021 @12:35AM (#27489776)
I was thinking about using bash, but couldn't come up with a solution to use tabcompletion when I'm in a different directory than the CSV file I want the data from, so I don'need to change directory.
Re:Ask HN: Tools you have made for yourself? by gnomewascool on Saturday June 12, 2021 @05:47PM (#27487686)
Not really, not if the CSV contains quoted newlines.
Re:Ask HN: Tools you have made for yourself? by asdw on Saturday June 12, 2021 @01:41PM (#27486094)
what does sq in sqhead mean?
Re:Ask HN: Tools you have made for yourself? by mikub on Sunday June 13, 2021 @12:38AM (#27489795)
Well, it actually doesn't "mean" anything. I just needed to come up with an alias for the command, so I wouldn't need to type it out all the time.
Re:Ask HN: Tools you have made for yourself? by softblush on Saturday June 12, 2021 @03:19PM (#27486821)
I guess the CSV files are SQL table dumps