python - gzip 将换行符写入文件 python

标签 python

我正在尝试在 python 中使用 gzip 将可迭代的元组写入文件。但是当我写换行符 (\n)

For example:
   if the iterable of tuples is like this: [(1,2,3) , (4,5)]
   the output file should be : 1,2,3
                               4,5

   but I got: 1,2,34,5



   I dont know where is my newline character gone!!!

   Here is my code: 
      fi = gzip.open(filename, "wb")
      for tup in data:
        fi.write(','.join(str(x) for x in tup).encode("utf-8"))
        fi.write("\n".encode("utf-8"))
      fi.close()

最佳答案

我只能假设您读取或显示未压缩数据的方式有问题?我在 Windows 和 Linux (Python 2.7) 上尝试了以下代码,它确实有效:

import gzip

filename = 'gzipout.gz'
data =  [(1,2,3) , (4,5)]
fi = gzip.open(filename, 'wb')
for tup in data:
    fi.write(','.join(str(x) for x in tup).encode("utf-8"))
    fi.write('\n'.encode("utf-8"))
fi.close()

fi = gzip.open(filename, 'rb')
unzipdata = fi.read()
print unzipdata
fi.close()

输出是:

1,2,3
4,5

此代码只是将内容 gzip 到一个文件,然后读回压缩数据并将其按原样转储到控制台。存在换行符。

如果我使用 gunzip gzipout.gz,它会提取到 gzipout,如果我显示内容,也会出现换行符。

您的行为并不少见,尤其是当您使用旧的脑死亡程序打开未压缩的文本文件时。在 *nix 世界中,行尾 (EOL) 通常\n 表示。在 Windows 中,EOL 由两个字符 \r\n 表示。 Python 具有用于编写文本的通用 模式,因此它会自动将\n 转换为平台上的任何EOL。不幸的是,GZIP 似乎仍然没有在 Python 2.7 中支持该标志。这意味着即使您打开 GZIP 文件以使用模式“U”(文本模式 + 通用)进行写入,每次写入也不会进行任何转换。

如果您在 Windows 平台上并针对 Windows 用户,那么您可能会考虑显式写入 '\r\n' 的非可移植解决方案,以便像记事本这样的脑残编辑器能够正确呈现。我猜这样的事情会产生你正在寻找的结果:

for tup in data:
    fi.write(','.join(str(x) for x in tup).encode("utf-8"))
    fi.write('\r\n'.encode("utf-8")) # notice I use \r\n instead of \n
fi.close()

关于python - gzip 将换行符写入文件 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25879758/

相关文章:

python - 在 DataFrame 中的新标题列下嵌套列

Python 使用 turtle 按钮

python - 如何在 pandas 中垂直堆叠列/系列

python - 如何使用 Waitress 和 Nginx 为本地应用程序提供服务

python - 循环中 "time.sleep"与 "threading.Timer"的资源使用情况

python - 如何在 Ubuntu 中安装指向自定义安装 Python3 的 Pip3?

python - 如何在 bash/Python/Fabric/sh 脚本中使用 pew?

python - 使用python修改fits文件时出现错误 "buffer is too small for requested array"

python - 如何用正则表达式可移植地解析(Unicode)度数符号?

python - 使用 gpu 在 ubuntu 16 上从源代码安装 tensorflow 的问题