【问题标题】:Concatenating text files creates file with space between each letter连接文本文件会创建每个字母之间有空格的文件
【发布时间】:2015-01-16 07:15:04
【问题描述】:

我尝试连接 txt 文件,几乎一切顺利,但是 输出文件的每个字母之间有一个空格 喜欢l o r e m i p s u m

这是我的代码

import glob

all = open("all.txt","a");

for f in glob.glob("*.txt"):
    print f
    t = open(f, "r")
    all.write(t.read())
    t.close()

all.close()

我正在使用 Windows 7,python 2.7

编辑
也许有更好的方法来连接文件?

EDIT2
我现在遇到了解码问题:

Traceback (most recent call last):
  File "P:\bwiki\BWiki\MobileNotes\export\999.py", line 9, in <module>
    all.write( t.read())
  File "C:\Python27\lib\codecs.py", line 671, in read
    return self.reader.read(size)
  File "C:\Python27\lib\codecs.py", line 477, in read
    newchars, decodedbytes = self.decode(data, self.errors)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xf3 in position 18: invalid
continuation byte


import codecs
import glob

all =codecs.open("all.txt", "a", encoding="utf-8")

for f in glob.glob("*.txt"):
    print f
    t = codecs.open(f, "r", encoding="utf-8")
    all.write( t.read())

【问题讨论】:

  • 使用简单的批处理命令连接文本文件的最佳方式。您可以简单地将文件添加在一起,就像它们是数字一样。
  • 我怀疑这个错误可能与您打开all.txt 两次这一事实有关。一次是分配给all,另一次是您在循环中打开它。 all.txt 将匹配全局 "*.txt"
  • @AlexBliskovsky 我认为这不会产生所描述的症状,但你说得对,这也是一个错误也是
  • @PlamZ 尝试使用type,效果相同 - 我将每个字母用空格分隔
  • 在 Python 中处理文件时最好使用the with statement

标签: python


【解决方案1】:

您的输入文件可能是 UTF 编码的,但您将其读取为 ASCII,这会导致出现空格(反映空字节)。试试:

import codecs

...

for f in glob.glob("*.txt"):
    print f
    t = codecs.open(f, "r", encoding="utf-16")

【讨论】:

    【解决方案2】:

    字母之间的“空格”可能表示至少有一些文件使用 utf-16 编码。

    如果所有文件都使用相同的字符编码,那么您可以使用cat(1) command,即将文件复制为字节 (code example in Python 3)。这是与您的 Python 代码相对应的cat PowerShell command

    PS C:\> Get-Content *.txt | Add-Content all.txt
    

    不同于cat *.txt &gt;&gt; all.txtIt should not corrupt the character encoding.

    如果您使用二进制文件模式,您的代码应该可以工作:

    from glob import glob
    from shutil import copyfileobj
    
    with open('all.txt', 'ab') as output_file:
        for filename in glob("*.txt"):
            with open(filename, 'rb') as file:
                copyfileobj(file, output_file)
    

    同样,所有文件都应具有相同的字符编码,否则您可能会在输出中得到垃圾(混合内容)。

    【讨论】:

      【解决方案3】:

      请运行此程序并将输出编辑到您的问题中(我们可能只需要查看前五行输出,左右)。它以十六进制打印每个文件的前 16 个字节。这将帮助我们弄清楚发生了什么。

      import glob
      import sys
      
      def hexdump(s):
          return " ".join("{:02x}".format(ord(c)) for c in s)
      
      l = 0
      for f in glob.glob("*.txt"):
          l = max(l, len(f))
      
      for f in glob.glob("*.txt"):
          with open(f, "rb") as fp:
             sys.stdout.write("{0:<{1}}  {2}\n".format(f, l, hexdump(fp.read(16))))
      

      【讨论】:

        猜你喜欢
        • 2021-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-03-26
        • 2015-05-22
        • 2013-08-29
        • 1970-01-01
        • 2018-02-12
        相关资源
        最近更新 更多