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()

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

posted @ 2019-07-06 09:50  吴吃辣  阅读(4705)  评论(0编辑  收藏  举报