gpt4 book ai didi

Python - CSV 写作 - 切断最后几行

转载 作者:行者123 更新时间:2023-12-01 03:00:45 25 4
gpt4 key购买 nike

我正在向 CSV 文件写入一个函数(正在运行),但是它在最后一行中被中途切断。我知道这可能与文件的关闭有关,但我认为我做得正确。

有什么可能出错的地方吗?

from itertools import combinations as cb 
import csv
import numpy as np


with open("usableReviewScores.csv") as f:
reader=csv.reader(f)
next(reader, None) # skip header
data=[filter(None,i) for i in reader]

writer = csv.writer(open("alexData1.csv", 'wb'))

def avgg(x):
ll=[float(i) for i in x[1:]] #take review no and convert to float
n=len(ll)
avg_list=[x[0]] #start result list with ref no.
final_list=[]
a = 0
b = []
c = []
d = []

global min_val
global max_val
min_val = 0
max_val = 0

for i in range(4,5):
for j in cb(ll,i):
# print(j)
c = i
avg_list.append(sum(j)/i)
final_list.append(sum(j)/i)
a = sum(final_list)/len(final_list)
min_val = min(final_list)
max_val = max(final_list)
d = np.std(final_list)

return (avg_list, "avg", a, "min", min_val, "max", max_val,
"Num of reviews", c, "std", d, "Total Reviews", n)

for x in data:
print(avgg(x))

for x in data:
writer.writerow(avgg(x))

最佳答案

你说这可能与文件的关闭有关。好吧,您实际上根本没有关闭输出文件。。所以我猜测这是文件系统缓存的症状,并且由于文件未关闭而缓存未正确刷新

您应该使用 with open(filename) 作为句柄: 进行书写和输入:

with open("alexData1.csv", 'wb') as outfile:
writer = csv.writer(outfile)
for x in data:
writer.writerow(avgg(x))

关于Python - CSV 写作 - 切断最后几行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43868218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com