【问题标题】:ValueError: I/O operation on closed file while loopingValueError:循环时对已关闭文件的 I/O 操作
【发布时间】:2017-05-05 03:58:01
【问题描述】:

您好,我在循环文件执行时遇到 I/O 错误。代码提示“ValueError: I/O operation on closed file”。在跑步的时候。有没有人知道当我在循环时打开新的操作时关闭操作?非常感谢

代码如下:

with open('inputlist.csv', 'r') as f:  #input list reading
    reader = csv.reader(f)
    queries2Google = reader
print(queries2Google)

def QGN(query2Google):
    s = '"'+query2Google+'"' #Keywords for query, to solve the + for space
    s = s.replace(" ","+")
    date = str(datetime.datetime.now().date()) #timestamp
    filename =query2Google+"_"+date+"_"+'SearchNews.csv' #csv filename
    f = open(filename,"wb")   #open output file

    pass

    df = np.reshape(df,(-1,3))
    itemnum,col=df.shape
    itemnum=str(itemnum)
    df1 = pd.DataFrame(df,columns=['Title','URL','Brief'])
    print("Done! "+itemnum+" pieces found.")

    df1.to_csv(filename, index=False,encoding='utf-8')
    f.close()

    return

for query2Google in queries2Google:
    QGN(query2Google) #output should be multiple files

【问题讨论】:

  • 我们可以得到一个行号吗?

标签: python python-3.x io


【解决方案1】:

with 在完成后关闭您尝试读取的文件。所以你正在打开文件,制作一个 csv 阅读器,然后关闭底层文件,然后尝试从中读取。查看更多关于文件 i/o here

解决方案是在 queries2Google 阅读器上使用 with 语句完成所有工作:

with open('inputlist.csv', 'r') as f:  #input list reading
    reader = csv.reader(f)
    for q2g in reader:
        QGN(q2g)

一些额外的东西:

pass 没有做任何事情,您可能应该在QGN 函数中再次使用with,因为文件在那里打开和关闭。 Python 不需要空返回。您似乎甚至没有在 QGN 函数中使用 f

【讨论】:

    猜你喜欢
    • 2013-09-27
    • 1970-01-01
    • 2016-07-21
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 2018-12-18
    • 2016-08-26
    • 2016-06-13
    相关资源
    最近更新 更多