如何从文件中读取内容?

5 投票
2 回答
9022 浏览
提问于 2025-04-17 09:11

我想用Python3来遍历一个文件夹里的文件,想把这些文件读成二进制对象(可能是字符串?),然后再进行一些后续处理。不过第一步是:怎么读取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

2 个回答

3

因为你的一些文件是二进制格式的,所以它们无法成功转换成Python 3用来存储所有字符串的unicode字符。要知道,Python 2和Python 3之间有一个很大的变化,就是字符串的表示方式从ASCII转变为unicode字符。这意味着每个字符不能简单地当作一个字节来处理(没错,Python 3中的文本字符串需要的内存是Python 2的2倍或4倍,因为UTF-8每个字符最多使用4个字节)。

因此,你有几个选择,这取决于你的项目需求:

在这种情况下,你可以修改你的解决方案,简单地捕获UnicodeDecode错误并跳过这个文件。

无论你做出什么决定,重要的是要注意,如果你系统中的文件有很多不同的字符编码,你需要指定编码,因为Python 3.0会默认认为字符是用UTF-8编码的。

作为参考,这里有一个关于Python 3输入输出的很棒的演示文稿: http://www.dabeaz.com/python3io/MasteringIO.pdf

9

要读取一个二进制文件,你必须以二进制模式打开这个文件。把

input = open(fullpath, "r")

改成

input = open(fullpath, "rb")

这样做后,read()的结果会是一个bytes()对象。

撰写回答