1、从文件中读取数据
# 要使用文本文件中的信息,首先需要将信息读取到内存中。我们可以一次性读取文件的全部内容,也可以以每次一行的方式逐步读取
2、读取整个文件
# open()函数,打开文件 ,第一个参数filered是需要打开文件的路径
# open()函数参数二:encoding='UTF-8' 设置编码格式,这样文件中有中文才不会乱码
# with 关键字,在不再需要访问文件后将其关闭,所以不需要自己手动close()关闭
# open()函数返回一个表示文件的对象,python将这个对象赋给了:file_obj 供以后使用
# file_obj.read() 使用read()方法读取这个文件的全部内容,并将其作为一个长长的字符串赋值给 content
# strip(): 用来去除头尾字符、空白符(包括\n、\r、\t、' ',即:换行、回车、制表符、空格)
# lstrip():用来去除开头字符、空白符(包括\n、\r、\t、' ',即:换行、回车、制表符、空格)
# rstrip():用来去除开头字符、空白符(包括\n、\r、\t、' ',即:换行、回车、制表符、空格)
with open('filered', encoding='UTF-8') as file_obj:
content = file_obj.read()
print(content.rstrip())
3、逐行读取文件内容
# 变量file_name表示并非实际的文件,只是告诉Python知道到哪里去查找文件的字符串
# 调用open()后,将文件及其内容赋给了变量:file_obj
# 使用with 关键字让python负责的打开和关闭文件
file_name = 'filered'
with open(file_name, encoding='UTF-8') as file_obj:
for content in file_obj:
print(content.strip()) # strip()去除字符串首位的空白
4、创建一个包含文件各行内容的列表
# 读取文件常用的三种方法 read,readline,readlines
# read() 读取整个文件
# readline() 读取下一行
# readlines() 读取整个文件到一个迭代器以供我们遍历(读取到一个list中,以供使用,比较方便)
# 遇到的错误:先是open一个文件,注意这时的句柄已经从文件的开头跑到文件的末尾去了。
# 所以如果再次read读取这个文件的话,会发现什么都没有, 第二次读取就什么也读不到了,所以要把句柄重新放回文件的开头,加一个f.seek(0)就解决了,修改后的代码:
4.1以下代码我们使用 readlines()读取整个文件生成列表对象:lines
print("----------------------")
file_name = 'filered'
with open(file_name, encoding='UTF-8') as file_obj:
lines = file_obj.readlines()
file_obj.seek(0) # 给这个文件添加句柄,放到文件开头,后面file_obj.readline()才能取到值
print(file_obj.readline().strip())
# 输出结果 :圆周率: 3.1415926535892743975437975945
for line in lines:
print(line.strip())
# 输出结果 :
# 圆周率: 3.1415926535892743975437975945
# gggggggggggggggg
# rrrrrrrrrrrr
4.2以下代码我们使用 read()读取整个文件赋值给变量lineall
with open(file_name, encoding='UTF-8') as file_obj:
lineall = file_obj.read()
print(lineall.strip())
# 输出结果 :
# 圆周率: 3.1415926535892743975437975945
# gggggggggggggggg
# rrrrrrrrrrrr
4.3以下代码我们使用 readline() 读取下一行赋值给变量linea
with open(file_name, encoding='UTF-8') as file_obj:
linea = file_obj.readline()
print(linea.strip())
# 输出结果 :
# 圆周率: 3.1415926535892743975437975945
---------------同级目录有一个名字为 'filered'文件,存储了信息如下
圆周率: 3.1415926535892743975437975945
gggggggggggggggg
rrrrrrrrrrrr