![](/img/trans.png)
[英]In Python when writing to a file how can you make sure the data is saved on one line?
[英]How to make sure Python goes into the end of a file line?
早上好, 由於 memory 問題,我正在嘗試在我的文件中逐行創建一個平均值 function 並計算我的文件每一列的平均值。 我的文件有 5000 列和 20000 行。 然而,當我打印這個 function 的 output 時,我列表的最后部分用零填充(我用來初始化它的值)。 我試着一個一個地寫出結果,但它一直寫到 4482 而不是 5000。有沒有辦法確保他一直寫到最后?
這是我的代碼:
def mean_by_line(file, size):
calc=[]
file=open(file,"r")
line=file.readline()
table_line=line.split(",")
mean_vector=[0 for i in range(len(table_line)-1)]
#We initialize the first one since we need it beforehand for the length
for j in range(len(table_line)-1):
calc.append(float(table_line[j]))
#We get the other values
for i in range(1,size):
line = file.readline()
table_line = line.split(",")
for j in range(len(table_line)-1):
calc[j]+= float(table_line[j])
#We calculate the average
for j in range(len(table_line)-1):
mean_vector[j]=calc[j]/size
print(j, mean_vector[j])
file.close()
return mean_vector
提前致謝
假設我們有一個包含逗號分隔數字的文件。 還假設每行的數字計數始終相同(但未知)並且我們想要找到每個“列”的算術平均值。
然后:
totals = None
line_count = 0
with open('atest.csv') as csv:
for line in map(str.strip, csv):
nums = line.split(',')
if totals is None:
totals = [0.0] * len(nums)
for i, v in enumerate(map(float, nums)):
totals[i] += v
line_count += 1
for i in range(len(totals)):
totals[i] /= line_count
print(totals)
非常感謝您的所有回答。 我再次檢查了輸入文件,奇怪的是,最后一行不像其他行那樣有 5k 列。 所以這是測量數據時的錯誤。 謝謝你,很抱歉我犯了這么嚴重的錯誤……
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.