Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-CSV写入-剪切最后一行_Python_Csv - Fatal编程技术网

Python-CSV写入-剪切最后一行

Python-CSV写入-剪切最后一行,python,csv,Python,Csv,我正在为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 heade

我正在为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))

你说这可能与关闭文件有关。实际上,您根本没有关闭输出文件。所以我猜这是文件系统缓存的一种症状,缓存没有被正确刷新,因为文件没有关闭

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

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

显示为的代码似乎存在缩进问题。特别是在“with open…as f”之后:“噢,对不起,那是我试图让网站接受它作为代码。让我编辑它以显示我的工具上的内容OK,编辑代码以匹配格式完美,谢谢。我已经测试过了,它可以工作了!:)