【问题标题】:How to replicate C# .read(buffer, 0, buffer.Length) in Python如何在 Python 中复制 C# .read(buffer, 0, buffer.Length)
【发布时间】:2017-01-26 00:04:16
【问题描述】:

昨天我问了一个关于文件流方法的类似问题What is the Python equivalent to FileStream in C#?,但我现在意识到我应该问的是 .read 函数。

对于上下文,我正在尝试使用来自soap API 的流式响应,它应该输出一个CSV 文件。响应输出一个以 base 64 编码的字符串,我不知道如何处理。 api文档还说必须将响应逐个读取到目标缓冲区。

这是代码中的上下文。代码由 api 的文档提供:

byte[] buffer = new byte[4000];
bool endOfStream = false;
int bytesRead = 0;
using (FileStream localFileStream = new FileStream(destinationPath, FileMode.Create, FileAccess.Write))
{
   using (Stream remoteStream = client.DownloadFile(jobId, chkFormatAsXml.Unchecked))
   {
     while (!endOfStream)
     {
         bytesRead = remoteStream.Read(buffer, 0, buffer.Length);
         if (bytesRead > 0)
         {
              localFileStream.Write(buffer, 0, bytesRead);
              totalBytes += bytesRead;
         }
         else
         {
              endOfStream = true;
         }
      }
   }
}

任何帮助都将不胜感激,即使只是为我指明正确的方向,因为我现在非常迷茫。我也有另一个问题,今天也提到了同样的问题。 Write Streamed Response(file-like object) to CSV file Byte by Byte in Python

【问题讨论】:

  • 只需执行remoteStream.read(n),其中n 是您想要阅读的内容。
  • 谢谢,你知道我如何一次读取一个缓冲区吗?
  • 什么是“缓冲区”?你知道它的大小吗?如果你这样做,只需读取那么多字节。
  • 既然你在 C#buffer.Length 中知道大小,那么在 Python 中也一定有办法找到它。所以,read(4000).
  • 肯定的。会的。

标签: c# python soap io


【解决方案1】:

看起来bytesread = len(openfile.read(4000)) 是复制bytesRead = remoteStream.Read(buffer, 0, buffer.Length); 的正确方法

感谢 DYZ

【讨论】:

    猜你喜欢
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 1970-01-01
    • 1970-01-01
    • 2015-08-25
    相关资源
    最近更新 更多