使用Python3,希望到os.walk
一个文件目录,将它们读入一个二进制对象(字符串?)并对它们做一些进一步的处理。第一步,但:如何阅读os.walk
的文件结果?如何从文件中读取文件内容?
# NOTE: Execute with python3.2.2
import os
import sys
path = "/home/user/my-files"
count = 0
successcount = 0
errorcount = 0
i = 0
#for directory in dirs
for (root, dirs, files) in os.walk(path):
# print (path)
print (dirs)
#print (files)
for file in files:
base, ext = os.path.splitext(file)
fullpath = os.path.join(root, file)
# Read the file into binary? --------
input = open(fullpath, "r")
content = input.read()
length = len(content)
count += 1
print (" file: ---->",base,"/",ext," [count:",count,"]", "[length:",length,"]")
print ("fullpath: ---->",fullpath)
错误:
Traceback (most recent call last):
File "myFileReader.py", line 41, in <module>
content = input.read()
File "/usr/lib/python3.2/codecs.py", line 300, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xe2 in position 11: invalid continuation byte
韩国社交协会,伦纳特 - 是的,这是秘密武器,我需要。有点新的Python3! – DrLou 2011-12-29 17:03:29
这实际上并不是Python的3特定。二进制文件也应该在Python 2中用'b'标志打开。 – 2011-12-29 20:20:45
是啊,回想起来,这一切似乎有点愚蠢 - 但这就是我们白痴学习的方式!你可能会想:RTFM!再次感谢您的帮助。 – DrLou 2014-11-03 21:17:34