簡體   English   中英

Python 文件處理/文件計數

[英]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()

不知道如果你像這樣縮進錯誤會發生什么:

在此處輸入圖像描述

但如果那是你的錯誤所在的地方,我猜這就是原因。 這就是你如何縮進 if-else:

for key in iplist.keys():
    line = "%-15s = %s" % (key, iplist[key])
    if  key in iplist:
         iplist[key] += 1
    else:
         iplist[key] = 1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM