Python读取txt文件内容(读取文件的六种方式)
Python 读取文件的六种方式
第一种:使用 open
常规操作
第二种:使用 fileinputwith open('data.txt') as fp: content = fp.readlines()
使用内置库 fileinput
第三种:使用 filecacheimport fileinput with fileinput.input(files=('data.txt',)) as file: content = [line for line in file]
使用内置库 filecache,你可以用它来指定读取具体某一行,或者某几行,不指定就读取全部行。
第四种:使用 codecsimport linecache content = linecache.getlines('werobot.toml')
使用 codecs.open 来读取
import codecs file=codecs.open("README.md", 'r') file.read()
如果你还在使用 Python2,那么它可以帮你处理掉 Python 2 下写文件时一些编码错误,一般的建议是:
在 Python 3 下写文件,直接使用 open
第五种:使用 io 模块使用 io 模块的 open 函数
import io file=io.open("README.md") file.read()
io.open和open是同一个函数
第六种:使用 os 模块Python 3.9.2 (default, Feb 28 2021, 17:03:44) [GCC 10.2.1 20210110] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> (open1:=open) is (open2:=os.open) False >>> import io >>> (open3:=open) is (open3:=io.open) True
os 模块也自带了 open 函数,直接操作的是底层的 I/O 流,操作的时候是最麻烦的
>>> import os >>> fp = os.open("hello.txt", os.O_RDONLY) >>> os.read(fp, 12) b'hello, world' >>> os.close(fp)
除注明外的文章,均为来源:老汤博客,转载请保留本文地址!
原文地址:https://tangjiusheng.com/it/681.html
原文地址:https://tangjiusheng.com/it/681.html
大家都在看
- numpy怎么安装(安装python环境及numpy插件的安装)
- 爬虫python入门好学吗(简单的爬虫案例适合入门学习)
- python怎么运行代码(教你运行代码程序方法)
- randint函数python的用法(随机模块22个函数详解)
- 在Python中//是什么意思(一文搞懂Python中的运算符)
- python数据类型有哪些(python六种数据结构介绍)
- python定义一个变量(教你python怎么声明一个变量)
- 全局变量和局部变量有什么区别(python中的全局变量和局部变量介绍)
- Python中valueerror是什么错误(异常处理千万别这么干)
- python输出语句print用法(基本输入输出语句print简介)