python - Condensing Repetitive Code -
i created simple application loads multiple csv's , stores them lists.
import csv import collections list1=[] list2=[] list3=[] l = open("file1.csv") n = open("file2.csv") m = open("file3.csv") csv_l = csv.reader(l) csv_n = csv.reader(n) csv_p = csv.reader(m) row in csv_l: list1.append(row) row in csv_n: list2.append(row) row in csv_p: list3.append(row) l.close() n.close() m.close() i wanted create function responsible this, avoid being repetitive , clean code thinking this.
def read(filename): x = open(filename) y = csv.reader(x) row in y: list1.append(row) x.close() however gets tough me when loop appends list. work append 1 list, if pass file name function append same list. not sure best way go this.
you need create new list each time, , return function:
def read(filename): rows = [] x = open(filename) y = csv.reader(x) row in y: rows.append(row) x.close() return rows then call follows
list1 = read("file1.csv") another option pass list in argument function - can choose whether create new list each time, or append multiple csvs same list:
def read(filename, rows): x = open(filename) y = csv.reader(x) row in y: rows.append(row) x.close() return rows # 1 list per file: list1 = [] read("file1.csv", list1) # multiple files combined 1 list: listcombined = [] read("file2.csv", listcombined) read("file3.csv", listcombined) i have used original code in answer, see malik brahimi's answer better way write function body using with , list(), , dogweather's comments - there lots of different choices here!
Comments
Post a Comment