Python - 如何读取带有 NUL 分隔行的文件?

标签 python nul

我通常使用以下 Python 代码从文件中读取行:

f = open('./my.csv', 'r')
for line in f:
    print line

但是如果文件是由“\0”(而不是“\n”)分隔的行呢?是否有可以处理此问题的 Python 模块?

感谢您的任何建议。

最佳答案

如果你的文件足够小,你可以将它全部读入内存,你可以使用拆分:

for line in f.read().split('\0'):
    print line

否则你可能想从关于这个 feature request 的讨论中尝试这个食谱:

def fileLineIter(inputFile,
                 inputNewline="\n",
                 outputNewline=None,
                 readSize=8192):
   """Like the normal file iter but you can set what string indicates newline.
   
   The newline string can be arbitrarily long; it need not be restricted to a
   single character. You can also set the read size and control whether or not
   the newline string is left on the end of the iterated lines.  Setting
   newline to '\0' is particularly good for use with an input file created with
   something like "os.popen('find -print0')".
   """
   if outputNewline is None: outputNewline = inputNewline
   partialLine = ''
   while True:
       charsJustRead = inputFile.read(readSize)
       if not charsJustRead: break
       partialLine += charsJustRead
       lines = partialLine.split(inputNewline)
       partialLine = lines.pop()
       for line in lines: yield line + outputNewline
   if partialLine: yield partialLine

我还注意到您的文件有一个“csv”扩展名。 Python 中内置了一个 CSV 模块(导入 csv)。有一个名为 Dialect.lineterminator 的属性然而,它目前还没有在阅读器中实现:

Dialect.lineterminator

The string used to terminate lines produced by the writer. It defaults to '\r\n'.

Note The reader is hard-coded to recognise either '\r' or '\n' as end-of-line, and ignores lineterminator. This behavior may change in the future.

关于Python - 如何读取带有 NUL 分隔行的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9237246/

相关文章:

python - AWS DynamoDB Python - 不从 table.scan() 返回属性

python - Python 中的 Null 字节表示

java - 空字符 (\u0000) 如何在字符串中结束?

sass - Sublime Text 返回 nul 控制字符

c++ - 当 NUL 字符定义为字符串的一部分时,为什么 strlen() 不计算终止 NUL 字符的字节数?

c - 在 C 中将 NULL 字符写入文件

python - Socketswift 连接到特定 IP 地址超时

python - Pyparsing - 从解析操作中解析子语法

python - 无法在windows上执行pyw

python - 转换为二进制会截断位