[英]Python file handling / counting amounts in file
此代碼是從文件中讀取,然后計算相同 ip 出現的次數和
將結果打印到我創建的名為 results.csv 的文件中,它正在打印到 python 上的電池,但不打印到文件中,並且計數器沒有加起來
infile = open("full_log.txt","r")
iplist = {} # create an empty dict
item_list ={}
for line in infile:
line = line.strip()
if line:
iplist.setdefault(line, 0) #
iplist[line] += 1 # increment
for key in iplist.keys():
line = "%-15s = %s" % (key, iplist[key])
if key in iplist:
# the count is not wokring
iplist[key] += 1
else:
iplist[key] = 1
print(line) # print uf desired.
item_list = [(k, v) for k, v in infile.items()]
# 2 Sort the list by v
item_list.sort(key=lambda x:x[1], reverse=True)
# it wont print to my file i have made
result_file = open("results.csv", "w")
for counter in range(1):
current_pair = item_list[counter]
result_file.write(current_pair[0] + "," + str(current_pair[1]) + "\n")
result_file.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.