Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A Python script that will return the number of rows and columns in a spreadsheet, list out the headers, and prompt the user for two columns to extract into a new csv file.
import csv
CSVfile = 'C:/Users/The CSV to Parse'
condCSVpath = 'C:/Users/The New CSV to Save'
#the .reader function returns a parsed list of rows
#Function counts number of rows
def HowManyRows(fp):
f = open(fp, encoding='utf8')
csv_f = csv.reader(f)
rowCount = 0
for row in csv_f:
rowCount = rowCount + 1
print("Number of Rows: " + str(rowCount))
f.close
#Function returns the column labels
def ColumnLabels(fp):
print("Columns: ")
f = open(fp, encoding='utf8')
csv_f = csv.reader(f)
rowCount= 0
for row in csv_f:
if rowCount < 1:
for x in range(len(row)):
print(str(x) + ": " + row[x])
rowCount = rowCount + 1
f.close
#Function returns the numbers of columns
def ColumnCount(fp):
f = open(fp, encoding='utf8')
csv_f = csv.reader(f)
rowCount= 0
for row in csv_f:
if rowCount < 1:
print("Column Count: " + str(len(row)))
rowCount = rowCount + 1
f.close
def CondenseCSV(FPathOrig, Fpath, row1, row2):
fnew = open(Fpath,'w')
f = open(FPathOrig, encoding='utf8')
csv_f = csv.reader(f)
for row in csv_f:
fnew.write(row[row1] + ',' +row[row2] + '\n')
fnew.close()
print ('Condensed CSV File Saved.')
HowManyRows(CSVfile)
ColumnCount(CSVfile)
ColumnLabels(CSVfile)
rowNumberToTransfer = int(input("Check list above for fields to transfer to condensed spreadsheet. Enter only numbers, not names.\n"))
rowNumberToTransfer2 = int(input("2nd Number.\n"))
CondenseCSV(CSVfile, condCSVpath, rowNumberToTransfer, rowNumberToTransfer2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.