Python读取txt文件内容(读取文件的六种方式)
Python 读取文件的六种方式
第一种:使用 open
常规操作
with open('data.txt') as fp: content = fp.readlines()
第二种:使用 fileinput
使用内置库 fileinput
import fileinput with fileinput.input(files=('data.txt',)) as file: content = [line for line in file]
第三种:使用 filecache
使用内置库 filecache,你可以用它来指定读取具体某一行,或者某几行,不指定就读取全部行。
import linecache content = linecache.getlines('werobot.toml')
第四种:使用 codecs
使用 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是同一个函数
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 模块
os 模块也自带了 open 函数,直接操作的是底层的 I/O 流,操作的时候是最麻烦的
>>> import os >>> fp = os.open("hello.txt", os.O_RDONLY) >>> os.read(fp, 12) b'hello, world' >>> os.close(fp)
THE END
二维码
打赏
共有 0 条评论