5 ms·
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.
by mikub 5y ago
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'
- asdw 5y agowhat does sq in sqhead mean?
- Madeindjs 5y agoThis can be done using two lines of Bash - `head -n 1 <file>` to get headers - `wc -l <file>` to count number of rows
- gnomewascool 5y agoNot really, not if the CSV contains quoted newlines.
- mikub 5y agoI 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.
- roveo 5y agoNice! 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(...)
- mikub 5y agoOh wow, that's a nice improvement. Thank you.