首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >关闭文件上的I/O操作(缩进问题) Python-Sockets

关闭文件上的I/O操作(缩进问题) Python-Sockets
EN

Stack Overflow用户
提问于 2016-05-16 01:56:04
回答 1查看 43关注 0票数 0

我有一个非常基本的问题。客户端完全接收到了文件并关闭了连接。服务器端在关闭文件和这行read(1024)时遇到了问题。也许我把它放在错误的位置了。我想我把while循环搞糊涂了。请指导我完成这件事。下面粘贴了简单的代码

代码语言:javascript
复制
while True:
    conn, addr = s.accept()     # Establish connection with client.
    print 'Got connection from', addr
    input = raw_input("Enter 1 for accessing file and 2 for editting")

    print(repr(input)) # printing input 
    if (input == "1"):
        filename= conn.recv(1024)
        f = open(filename,'rb')
        l = f.read(1024)

    while (1): #Keep sending it until EOF id found
        conn.send(l) #Keep sending the opened file
        print(repr(l)) 
        l = f.read(1024)
        f.close()
EN

回答 1

Stack Overflow用户

发布于 2016-06-20 20:09:22

在您的while循环中,您将关闭该文件,并在下一个循环周期中尝试读取该文件,因此您会得到错误I/O operation on closed file。除了放错位置的f.close()之外,您的循环还缺少一个中断条件。更好地替换

代码语言:javascript
复制
        l = f.read(1024)

    while (1): #Keep sending it until EOF id found
        conn.send(l) #Keep sending the opened file
        print(repr(l)) 
        l = f.read(1024)
        f.close()

使用

代码语言:javascript
复制
    for l in iter(lambda: f.read(1024), ''): #Keep sending it until EOF id found
        conn.send(l)                         #Keep sending the opened file
    conn.close()
    f.close()
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37241746

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档