use*_*596 3 python file-io traceback python-3.x python-unicode
以下是示例代码,目的只是合并来自give文件夹及其子文件夹的文本文件.我偶尔会得到Traceback所以不知道在哪里看.还需要一些帮助来增强代码以防止空行被合并并在合并/主文件中不显示任何行.在合并文件之前,可能需要进行一些清理或者在合并过程中忽略空行,这可能是个好主意.
文件夹中的文本文件不超过1000行,但聚合主文件可以非常容易地跨越10000多行.
import os
root = 'C:\\Dropbox\\ans7i\\'
files = [(path,f) for path,_,file_list in os.walk(root) for f in file_list]
out_file = open('C:\\Dropbox\\Python\\master.txt','w')
for path,f_name in files:
in_file = open('%s/%s'%(path,f_name), 'r')
# write out root/path/to/file (space) file_contents
for line in in_file:
out_file.write('%s/%s %s'%(path,f_name,line))
in_file.close()
# enter new line after each file
out_file.write('\n')
with open('master.txt', 'r') as f:
lines = f.readlines()
with open('master.txt', 'w') as f:
f.write("".join(L for L in lines if L.strip()))
Traceback (most recent call last):
File "C:\Dropbox\Python\master.py", line 9, in <module> for line in in_file:
File "C:\PYTHON32\LIB\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 972: character maps to <undefined>
Run Code Online (Sandbox Code Playgroud)
抛出错误是因为Python 3使用与内容不匹配的默认编码打开文件.
如果你所做的只是复制文件内容,最好在二进制模式下打开文件时使用该shutil.copyfileobj()功能.这样就可以完全避免编码问题(当然,只要你的所有源文件都是相同的编码,所以你不会得到带有混合编码的目标文件):
import shutil
import os.path
with open('C:\\Dropbox\\Python\\master.txt','wb') as output:
for path, f_name in files:
with open(os.path.join(path, f_name), 'rb') as input:
shutil.copyfileobj(input, output)
output.write(b'\n') # insert extra newline between files
Run Code Online (Sandbox Code Playgroud)
我已经清理了一些代码以使用上下文管理器(因此您的文件在完成后会自动关闭)并os.path用于创建文件的完整路径.
如果你确实需要逐行处理你的输入,你需要告诉Python期望的编码,所以它可以将文件内容解码为python字符串对象:
open(path, mode, encoding='UTF8')
Run Code Online (Sandbox Code Playgroud)
请注意,这需要你知道前面是什么编码的文件使用.
如果您对python 3,文件和编码有更多疑问,请阅读Python Unicode HOWTO.
小智 5
我在使用 os 模块删除功能删除文件时遇到了类似的问题。
\n我执行的所需更改是:
\nfile = open(filename)\nRun Code Online (Sandbox Code Playgroud)\n到
\nfile = open(filename, encoding="utf8")\nRun Code Online (Sandbox Code Playgroud)\n添加编码=\xe2\x80\x9cutf-8\xe2\x80\x9d
\nUTF-8 是最常用的编码之一,Python 通常默认使用它。UTF 代表 \xe2\x80\x9cUnicode Transformation Format\xe2\x80\x9d,而 \'8\' 表示在编码中使用 8 位值。... UTF-8 使用以下规则:如果代码点 < 128,则由相应的字节值表示。
\n| 归档时间: |
|
| 查看次数: |
18375 次 |
| 最近记录: |