Sử dụng Python3, hy vọng os.walk
một thư mục tệp, đọc chúng thành đối tượng nhị phân (chuỗi?) Và thực hiện thêm một số thao tác trên chúng. Bước đầu tiên, mặc dù: Làm thế nào để đọc các tập tin (s) kết quả của os.walk
?Cách đọc nội dung tập tin từ một tập tin?
# 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)
LỖI:
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
Tks, Lennart - Vâng, đây là nước sốt bí mật tôi cần. Kinda mới với Python3! – DrLou
Nó không thực sự Python 3 cụ thể. Các tệp nhị phân sẽ được mở bằng cờ 'b' trong Python 2. –
Vâng, tất cả dường như hơi câm với tôi khi nhìn lại - nhưng đây là cách chúng tôi ngốc nghếch học hỏi! Có lẽ bạn đang nghĩ: RTFM! Cảm ơn một lần nữa để được giúp đỡ. – DrLou