csv - With statement being ignored in Python -


i have 2 functions. first creates new csv file (from existing csv). second appends same data new csv, in different order of rows.

when run in 1 file first function works second not. when tried putting second function in separate file calling in first script, did work, albeit had enter input twice.

what need change second function run properly?

import csv export = raw_input('>') new_file = raw_input('>')  ynabfile = open(export, 'rb') reader = csv.reader(ynabfile)  def create_file():     open(new_file, 'wb') result:         writer = csv.writer(result)         r in reader:             writer.writerow((r[3], r[5], r[6],r[7], r[7],                 r[8],r[8],r[9],r[10]))  def append():     open(new_file, 'ab') result2:         writer2 = csv.writer(result2)         in reader:             writer.writerow((r[3], r[5], r[6], r[7], r[7],                 r[8], r[8], r[10], r[9]))  create_file()  append() 

i'm new python , programming in general, if there around better way this, i'm ears.

the csv reader has read entire file pointed ynabfile, on second call (or subsequent calls) either create_file or append not able fetch more data using reader until file pointer sent beginning. in case, quick fix this:

create_file() ynabfile.seek(0) append() 

i recommend restructuring code bit avoid pitfalls this. few recommendations:

  • read contents in ynabfile list instead, if can fit entirety of file memory
  • have create_file , append take parameter of input , output file names
  • alternatively, have 2 functions take file pointer (ynabfile in case), , ensure seeked beginning create new csv.reader instance using that.

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -