我有一个csv文件,如下所示:
CCC, rev, pIndex, no.
23, 2.5, 0, 4
34, 4.3, 1, 3
27, 7.9, 2, 5
12, 5.7, 3, 7其中,每行中的第三个元素称为pIndex。我的代码将每行复制一次,同时相应地更新pIndex。因此,输出如下所示:
CCC, rev, pIndex, no.
23, 2.5, 0, 4
23, 2.5, 1, 4
34, 4.3, 2, 3
34, 4.3, 3, 3
27, 7.9, 4, 5
27, 7.9, 5, 5
12, 5.7, 6, 7
12, 5.7, 7, 7下面是执行此操作的代码:
with fileinput.input(inplace=True) as f:
n = 0
for line in f:
line = line.rstrip('\n')
numbers = line.split(sep = ',')
for i in range(2):
numbers[3] = n
n += 1
s = ''
for j in numbers:
s += str(j) + ','
s = s.rstrip(',')
print(s)现在我想删除第一行和最后一行中的一个重复项,所以基本上删除文件中的第一行(在header之后,使用pIndex 0)和最后一行。我正在使用fileinput并尝试将结果写回同一个文件中。
发布于 2017-08-14 22:24:29
在读入行时,您可以将它们存储在一个数组中,并省略要删除的行。然后将数组写入文件。
您可以使用csv library写入csv,例如如下所示:
import csv
with open('some.csv', 'wb') as f:
writer = csv.writer(f)
writer.writerows(someiterable)https://stackoverflow.com/questions/45676595
复制相似问题