我创建了一个简单的应用程序来加载多个 csv 并将它们存储到列表中。
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)
for row in csv_l:
list1.append(row)
for row in csv_n:
list2.append(row)
for row in csv_p:
list3.append(row)
l.close()
n.close()
m.close()
我想创建一个函数来负责这个,这样我就可以避免重复并清理代码,所以我在想这样的事情。
def read(filename):
x = open(filename)
y = csv.reader(x)
for row in y:
list1.append(row)
x.close()
但是,当我到达附加到列表的 for 循环时,它变得很困难。这可以附加到 1 个列表,但是如果我将另一个文件名传递给函数,它将附加到同一个列表。不确定解决此问题的最佳方法。
最佳答案
你只需要每次创建一个新列表,并从你的函数中返回它:
def read(filename):
rows = []
x = open(filename)
y = csv.reader(x)
for row in y:
rows.append(row)
x.close()
return rows
然后调用如下
list1 = read("file1.csv")
另一种选择是将列表作为参数传递给您的函数 - 然后您可以选择是每次都创建一个新列表,还是将多个 CSV 附加到同一个列表:
def read(filename, rows):
x = open(filename)
y = csv.reader(x)
for row in y:
rows.append(row)
x.close()
return rows
# One list per file:
list1 = []
read("file1.csv", list1)
# Multiple files combined into one list:
listCombined = []
read("file2.csv", listCombined)
read("file3.csv", listCombined)
我在我的回答中使用了您的原始代码,但另请参阅 Malik Brahimi 的回答,了解使用 with
和 list()
编写函数体本身的更好方法,和 DogWeather 的评论 - 这里有很多不同的选择!
关于python - 压缩重复代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29377133/