【发布时间】: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
withstatement。
标签: python