Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/actionscript-3/7.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
File 在python中编写一个文件_File_Python 2.7_Sockets - Fatal编程技术网

File 在python中编写一个文件

File 在python中编写一个文件,file,python-2.7,sockets,File,Python 2.7,Sockets,我在一个输入文件中保存了多个段。格式为: Use case 1: host port start_byte end_byte 127.0.0.1 12345 0 2048 127.0.0.1 12346 0 1024 127.0.0.1 12347 1024 2048 Use case 2: host port start_by

我在一个输入文件中保存了多个段。格式为:

  Use case 1:

  host        port    start_byte     end_byte 
 127.0.0.1   12345   0              2048
 127.0.0.1   12346   0              1024
 127.0.0.1   12347   1024           2048

 Use case 2:

 host        port    start_byte     end_byte 
 127.0.0.1   12345   0              2048
 127.0.0.1   12346   1024           2048
 127.0.0.1   12347   0              1024
这里,第一行用于参考,以了解每一行的内容。 主机是本地主机,但端口不同

这里有3个端口。端口#12345包含整个文件(比如abc.txt)。端口#12347已关闭 第二段,而端口#12346具有第一段

现在,我想从文件末尾到文件开头(从第3行到第1行)读取文件

下载每个段并写入新文件的代码如下所示

 def downloadSegment(threadName, fileNameTemp, server_addr, server_port, segment_beginaddr, segment_endaddr, fileName, maxSegmentSize,ip_address,peer_server_port, relevant_path):

      downloadSegmentStr = "download," + fileName + ","+segment_beginaddr+"," + segment_endaddr   
      socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      socket1.connect((server_addr, int(server_port)))
      socket1.send(downloadSegmentStr)

      lock.acquire()
      with open(fileNameTemp, 'ab') as file_to_write:   
          file_to_write.seek(int(segment_beginaddr),0)
          while True:
          data = socket1.recv(maxSegmentSize)
          #print data
          if not data:
            break

          #print data
          file_to_write.write(data)
     file_to_write.close()
     lock.release();
     socket1.close()
当我以递增的顺序编写段(用例1)时,它工作得非常好。但是,当我尝试按顺序使用
时,就像上面用例2中解释的那样,它不起作用


感谢您的帮助。谢谢。

您错过了Python文档的以下部分:

'a'
用于附加(在某些Unix系统上,这意味着 写入附加到文件末尾,而不考虑当前搜索 位置)

…请注意,如果打开文件进行附加(模式
'a'
'a+'
), 任何
seek()
操作都将在下次写入时撤消。如果文件是 仅在附加模式(模式
'a'
)下打开写入,此方法是 基本上是一个禁止

因此,模式
'a'
不适合该任务。遗憾的是,
stdio
fopen()
没有一种模式没有
a
,该模式在文件不存在时创建文件,在文件存在时不截断文件。所以我会使用
os.open()
类似于:

    with os.fdopen(os.open(fileNameTemp, os.O_CREAT|os.O_WRONLY), 'wb') as file_to_write: