Python 读文件

版权所有,未经许可,禁止转载


章节

Python 介绍
Python 开发环境搭建
Python 语法
Python 变量
Python 数值类型
Python 类型转换
Python 字符串(String)
Python 运算符
Python 列表(list)
Python 元组(Tuple)
Python 集合(Set)
Python 字典(Dictionary)
Python If … Else
Python While 循环
Python For 循环
Python 函数
Python Lambda
Python 类与对象
Python 继承
Python 迭代器(Iterator)
Python 模块
Python 日期(Datetime)
Python JSON
Python 正则表达式(RegEx)
Python PIP包管理器
Python 异常处理(Try…Except)
Python 打开文件(File Open)
Python 读文件
Python 写文件
Python 删除文件与文件夹


打开本地文件

假设在本地当前目录下有以下文件:

test.txt

High in the halls of the kings who are gone
Jenny would dance with her ghosts
The ones she had lost and the ones she had found
And the ones who had loved her most
The one who'd heen gone for so very long

使用内置的open()函数打开文件。

open()函数会返回一个文件对象,它有一个read()方法用来读取文件内容:

示例

f = open("test.txt", "r")

print(f.read())

读取文件的部分内容

默认情况下,read()方法将读取全部内容,但也可以指定要读取多少字符:

示例

读取文件的前10个字符:

f = open("test.txt", "r")
print(f.read(10))

按行读取

您可以使用readline()方法读取一行:

示例

读取一行:

f = open("test.txt", "r")
print(f.readline())

通过调用两次readline(),可以读取两行:

示例

读取2行:

f = open("test.txt", "r")
print(f.readline())
print(f.readline())

可以通过循环,逐行读取整个文件:

示例

逐行读取文件:

f = open("test.txt", "r")
for x in f:
  print(x)

关闭文件

当处理完文件后,应该关闭文件,释放资源。

示例

完成文件处理后,关闭文件:

f = open("test.txt", "r")
print(f.readline())
f.close()

注意: 完成文件处理后,应该关闭文件,释放资源。某些情况下,由于缓存,对文件所做的更改不会立即显示,直到关闭文件再重新打开。

你可能感兴趣的:(Python 读文件)