【发布时间】:2017-09-24 23:17:30
【问题描述】:
过去 8 个月我只使用 Python 编程,所以请原谅我对 Python 可能是新手。
我的问题如下,希望有人能帮我解决。
我在一个文件中有很多数据,例如这样的(只是一个片段):
SWITCH MGMT IP;SWITCH HOSTNAME;SWITCH MODEL;SWITCH SERIAL;SWITCH UPTIME;PORTS NOT IN USE
10.255.240.1;641_HX_3560X;WS-C3560X-24P-S;FDO1601V031;12 weeks, 3 days, 23 hours, 33 minutes;1
10.255.240.7;641_HX_LEFT_2960x;WS-C2960X-24PS-L;FOC1750S2E5;12 weeks, 4 days, 7 minutes;21
10.255.240.8;641_UX_BASEMENT_2960x;WS-C2960X-24PS-L;FOC1750S2AG;12 weeks, 4 days, 7 minutes;12
10.255.240.9;641_UX_SPECIAL_2960x;WS-C2960X-24PS-L;FOC1750S27M;12 weeks, 4 days, 8 minutes;25
10.255.240.2;641_UX_OFFICE_3560;WS-C3560-8PC-S;FOC1202U24E;2 years, 30 weeks, 3 days, 16 hours, 43 minutes;2
10.255.240.3;641_UX_SFO_2960x;WS-C2960X-24PS-L;FOC1750S2BR;12 weeks, 4 days, 7 minutes;14
10.255.240.65;641_HX_3560X;WS-C3560X-24P-S;FDO1601V031;12 weeks, 3 days, 23 hours, 34 minutes;1
10.255.240.5;641_HX_RIGHT_2960s;WS-C2960S-24PS-L;FOC1627X1BF;12 weeks, 4 days, 12 minutes;16
10.255.240.6;641_HX_LEFT_2960x-02;WS-C2960X-24PS-L;FOC1750S2C4;12 weeks, 4 days, 7 minutes;15
10.255.240.4;641_UX_BASEMENT_2960s;WS-C2960S-24PS-L;FOC1607Z27T;12 weeks, 4 days, 8 minutes;3
10.255.240.62;641_UX_OFFICE_3560CG;WS-C3560CG-8PC-S;FOC1646Y0U2;15 weeks, 5 days, 12 hours, 15 minutes;6
我想遍历文件中的所有数据并检查序列号是否出现多次。如果确实如此,我想删除找到的重复项。结果可能多次包含同一个交换机或路由器的原因是它可能有多个第 3 层接口,可以在其中对其进行管理。
所以在上面的例子中。在我浏览完数据后,它应该删除该行:
10.255.240.65;641_HX_3560X;WS-C3560X-24P-S;FDO1601V031;12 weeks, 3 days, 23 hours, 34 minutes;1
由于文件中的第二行已经包含相同的开关和序列号。
我花了几天时间试图弄清楚如何实现这一点,这让我开始头疼。
我的基本代码如下所示:
if os.stat("output.txt").st_size != 0:
with open('output.txt','r') as file:
header_line = next(file) # Start from line 2 in the file.
data = [] # Contains the data from the file.
sn = [] # Contains the serial numbers to check up against.
ok = [] # Will contain the clean data with no duplicates.
data.append(header_line.split(";")) # Write the head to data.
for line in file: # Run through the file data line for line.
serialchk = line.split(";") # Split the data into a list
data.append(serialchk) # Write the data to data list.
sn.append(serialchk[3]) # Write the serial number to sn list.
end = len(data) # Save the length of the data list, so i can run through the data
i = 0 # For my while loop, so i know when to stop.'
while i != end: # from here on out i am pretty lost on how to achieve my goal.
found = 0
for x in range(len(data)):
if sn[i] == data[x][3]:
found += 1
print data[x]
ok.append(data[x])
elif found > 1:
print "Removing:\r\n"
print data[x-1]
del ok[-1]
found = 0
i += 1
有没有更蟒蛇的方式来做到这一点?我很确定这里所有有才华的人,有人可以给我线索,告诉我如何实现这一目标。
提前非常感谢您。
【问题讨论】:
-
首先,我会查看
csvmodule
标签: python list file save append