gpt4 book ai didi

python - 如何从文件中读取文件内容?

转载 作者:太空狗 更新时间:2023-10-30 00:33:31 30 4
gpt4 key购买 nike

使用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

最佳答案

要读取二进制文件,您必须以二进制模式打开文件。变化

input = open(fullpath, "r")

input = open(fullpath, "rb")

read() 的结果将是一个 bytes() 对象。

关于python - 如何从文件中读取文件内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8662641/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com