python - Appending a "0" to the beginning of a cell in a CSV file? -
to specific, i've got list of 2000 fips codes (example: "8001007801") in single column of csv file. of these codes should begin 0, default excel formats cells remove "0" values @ origin of cell contains numbers. know how format when i'm printing not when i'm writing file.
i need script go through first cell in each row, place "0" @ front end of it, , re-create row new output csv. here have far:
import csv infile = open("fips_original.csv", "r") reader = csv.reader(infile, delimiter = ";", quotechar = '"') outfile = open("fips_appended.csv", "w") author = csv.writer(outfile, delimiter = ";", quotechar = '"') row in reader: outrow = list(row) outrow[0] = outrow[0].zfill(11) writer.writerow(outrow) infile.close() outfile.close() all script @ point re-create same values output csv, not append "0". can help out this? please allow me know if need more information, , in advance.
edit: should note when utilize print function print values in python idle, come out formatted correctly. should note have unchecked excel setting automatically formats text cells no alphabetical characters numbers, , have tried formatting of cells in both spreadsheets numbers.
answer: turns out indeed formatting issue in excel. changing cell type text nil if disable alternative automatically changes text cells numbers number cells. have custom format cell hold many characters need (which doesn't solve if of numbers in column different characters). link explains how it: http://superuser.com/questions/88870/adding-a-zero-before-values-in-an-excel-spreadsheet-column
thanks help - 1 time plenty time has passed me post reply own question will.
try this:
import csv fn_in="/tmp/fips_original.csv" fn_out="/tmp/fips_appended.csv" open(fn_in, "r") infile, open(fn_out, 'w') outfile: reader = csv.reader(infile, delimiter = ";", quotechar = '"') author = csv.writer(outfile, delimiter = ";", quotechar = '"') header=next(reader) writer.writerow(header) row in reader: row[0] = row[0].zfill(11) writer.writerow(row) the behavior describing probably because csv not parsing each column in each row list. seek putting in print statement create sure delimiter , quote characters correct.
python excel python-2.7 csv formatting
No comments:
Post a Comment