def read_file():
with open("bla.csv", "r") as Blabla:
reader = csv.reader(BlaBla)
for column in reader:
one = column[1]
two = column[2]
three = column[3]
four = column[4]
bla_line.append([one, two, three, four])
count, c = 50, 1
while c < count:
read_file()
c = c + 1
在循环时如何逐行读取文件?每c
一行。
c = 0 = read line 0
c = 1 = read line 1
c = 2 = read line 2
以此类推...
islice
,pandas
等,到目前为止,对我来说还没有解决。
我需要这个构造完全一样,因为这里没有列出其他功能和以后的操作。
到目前为止append
操作正常。这里的问题是像我描述的那样遍历文件。
答案 0 :(得分:0)
希望这将逐行读取csv
文件
with open("bla.csv") as f:
lis = [line.split() for line in f] # create a list of lists
for i, x in enumerate(lis): #print the list items
print "line{0} = {1}".format(i, x))
答案 1 :(得分:0)
此解决方案是逐行读取csv文件,并返回代表原始csv文件的列表列表。
def read_csv(path: str, ignore_headers: bool = False):
with open(path, 'r') as csv:
res = []
for line_number, line in enumerate(csv.readlines()):
if ignore_headers and line_number == 0:
continue
else:
res.append(line.strip().split(','))
return res
if __name__ == '__main__':
csv_content = '''first_name,last_name,age
John,Harris,23
Omar,Ahmed,19'''
with open('temp.csv', 'w') as _file:
for line in csv_content:
_file.write(line)
csv = read_csv('temp.csv')
print(csv)
csv = read_csv('temp.csv', ignore_headers=True)
print(csv)
希望它会有所帮助!