Mac系统解除UnicodeDecodeError: ‘utf

阅读: 评论:0

Mac系统解除UnicodeDecodeError: ‘utf

Mac系统解除UnicodeDecodeError: ‘utf

file_path = "xxx"
files = os.listdir(file_path)
contents = []
for file in files:file_p = os.path.join(file_path, file)with open(file_p, 'r', encoding='utf-8') as f:a = f.read()[:200]contents.append(a)

在读取txt文件时发现总是报错

但是我的文件确定是使用utf-8编码的文件,查了一下原来是mac系统的系统文件ds_store搞怪

参考了这位博主提出的方法:UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 3131: invalid start byte解决办法_dadan9的博客-CSDN博客

解决办法是:使用命令行进入当读取文件所在文件夹,删除.DS_Store文件。

1. 使用命令ls -a可以查看到.DS_Store文件

2. rm .DS_Store。

但我在删除后,通过ls -a发现也没有ds文件了,但发现还是不行,照样报错

后直接在代码加了一步:

print(files)

发现在代码运行时ds文件又自动产生了。

['.DS_Store', '', &#']

于是提出解决方法:通过文件判断跳过ds文件。

for file in files:  # 检查文件是否为txt文件  if os.path.splitext(file)[-1] == '.txt':  file_p = os.path.join(file_path, file)  with open(file_p, 'r', encoding='utf-8') as f:  a = f.read()[:200]  contents.append(a)

本文发布于:2024-01-29 13:50:56,感谢您对本站的认可!

本文链接:https://www.4u4v.net/it/170650746015724.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:系统   Mac   utf   UnicodeDecodeError
留言与评论(共有 0 条评论)
   
验证码:

Copyright ©2019-2022 Comsenz Inc.Powered by ©

网站地图1 网站地图2 网站地图3 网站地图4 网站地图5 网站地图6 网站地图7 网站地图8 网站地图9 网站地图10 网站地图11 网站地图12 网站地图13 网站地图14 网站地图15 网站地图16 网站地图17 网站地图18 网站地图19 网站地图20 网站地图21 网站地图22/a> 网站地图23