鱼C论坛

 找回密码
 立即注册
查看: 2842|回复: 0

[学习笔记] Python文件读取的练习收获分享!

[复制链接]
发表于 2021-2-22 16:50:40 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
在做如何读取txt文件内容的练习时,遇到了一些问题,后经搜索、分析、学习,觉得有些收获,记录一下,也希望能够帮助到遇到同样问题的同学。

两个问题:
1、txt文件中有中文时,会报这个错误
UnicodeDecodeError: 'gbk' codec can't decode byte 0xad in position 87: illegal multibyte sequence
解决方法很简单,在打开文件时加上编码属性即可
with open(dir, 'r',encoding = 'utf-8') as f:

2、文件(f)用 for...in... 结构迭代时,f.readline()的读取问题,大家自己可以分析一下第三个函数 readFileText3(),其实很简单。

程序示例:
  1. def readFileText1(dir):
  2.     texts = []
  3.     with open(dir, 'r',encoding = 'utf-8') as f:
  4.         for line in f:
  5.             texts.append(line.strip('\n'))
  6.     return texts

  7. #==================================================================

  8. def readFileText2(dir):
  9.     texts = []
  10.     with open(dir, 'r',encoding = 'utf-8') as f:
  11.         for i in range(0, 10):
  12.             texts.append(f.readline().strip('\n'))
  13.     return texts

  14. #===================================================================

  15. def readFileText3(dir):
  16.     texts = []
  17.     with open(dir, 'r',encoding = 'utf-8') as f:
  18.         for line in f:
  19.             texts.append(f.readline().strip('\n'))
  20.     return texts

  21. textdir = 'D:\\PythonTest\\IDLE\\testone.txt'
  22. filetexts1 = readFileText1(textdir)
  23. filetexts2 = readFileText2(textdir)
  24. filetexts3 = readFileText3(textdir)
  25. print(filetexts1)
  26. print('=============================================')
  27. print(filetexts2)
  28. print('*********************************************')
  29. print(filetexts3)
复制代码


运行结果
  1. #运行结果

  2. ['dfdfdsfasf', 'sdfweewrewrkl', 'dsf[ospo', 'sdflkjj', 'kl;ipm,.m,', 'xiuuyifdyu', 'syuywwpoqasdf', '中文实例']
  3. =============================================
  4. ['dfdfdsfasf', 'sdfweewrewrkl', 'dsf[ospo', 'sdflkjj', 'kl;ipm,.m,', 'xiuuyifdyu', 'syuywwpoqasdf', '中文实例', '', '']
  5. *********************************************
  6. ['sdfweewrewrkl', 'sdflkjj', 'xiuuyifdyu', '中文实例']
复制代码


小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-6 05:15

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表