我正在从CSV文件中读取并将行添加到列表中。有一些空格导致我的脚本出现问题。我需要从列表中删除那些已经设法删除的空格。但是,有人可以建议这样做是否正确吗?
ip_list = []
with open('name.csv') as open_file:
read_file = csv.DictReader(open_file)
for read_rows in read_file:
ip_list.append(read_rows['column1'])
ip_list = list(filter(None, ip_list))
print(ip_list)
还是一个函数会更可取?
答案 0 :(得分:0)
这是读取csv文件并将其存储在列表中的好方法。
L=[] #Create an empty list for the main array
for line in open('log.csv'): #Open the file and read all the lines
x=line.rstrip() #Strip the \n from each line
L.append(x.split(',')) #Split each line into a list and add it to the
#Multidimensional array
print(L)
例如,此csv文件将产生类似
的输出This is the first line, Line1
This is the second line, Line2
This is the third line, Line3
这个
List = [('This is the first line', 'Line1'),
('This is the second line', 'Line2'),
('This is the third line', 'Line3')]
因为csv表示逗号分隔的值,您可以根据逗号进行过滤