python - Edit a piece of data inside a csv -


i have csv file looking this

34512340,1 12395675,30 56756777,30 90673412,45 12568673,25 22593672,25 

i want able edit data after comma python , save csv.

does know how able this? bit of code below write new line, not edit:

f = open("stockcontrol","a") f.write(code) 

here sample, adds 1 second column:

import csv  open('data.csv') infile, open('output.csv', 'wb') outfile:     reader = csv.reader(infile)     writer = csv.writer(outfile)     row in reader:         # transform second column, row[1]         row[1] = int(row[1]) + 1         writer.writerow(row) 

notes

  • the csv module correctly parses csv file--highly recommended
  • by default, each row parsed text, why converted integer: int(row[1])

update

if want edit file "in place", use fileinput module:

import fileinput  line in fileinput.input('data.csv', inplace=true):     fields = line.strip().split(',')     fields[1] = str(int(fields[1]) + 1)  # "update" second column     line = ','.join(fields)     print line  # write line file, in place 

Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -

java - Digest auth with Spring Security using javaconfig -