Python文件操作函数:readlines()
发布时间:2023-06-09 16:31:22
Python文件操作中的readlines()函数是将整个文件内容读取到一个列表中的函数。该函数会将读取到文件的数据分行存储到一个列表中。
下面是readlines()函数的语法:
file.readlines(sizehint)
其中,sizehint是可选参数,表示希望读取的字节数。如果sizehint省略,则会读取整个文件。
下面是readlines()函数的示例:
假设我们有一个名为test.txt的文本文件,其中包含如下内容:
This is a test file. The file contains some text. We will use this file to demonstrate the use of readlines() function in Python.
我们可以使用如下代码使用readlines函数将文件读取到一个列表中:
with open('test.txt') as f:
lines = f.readlines()
print(lines)
运行结果如下:
['This is a test file. ', 'The file contains some text. ', 'We will use this file to demonstrate the use of readlines() function in Python. ']
我们可以看到,readlines()函数返回了一个包含每行内容的字符串的列表。每行的结尾都被换行符
所分割。
我们还可以使用sizehint参数指定读取的字节数。例如,下面使用sizehint参数读取文件的前10个字节:
with open('test.txt') as f:
lines = f.readlines(10)
print(lines)
运行结果如下:
['This is a ']
我们可以看到,readlines()函数只返回了前10个字节的内容(即一部分内容),并没有返回整个文件。
总的来说,readlines()函数是Python文件操作中一个非常有用的函数,它可以帮助我们快速将整个文件内容读取到一个列表中,方便我们进行后续操作。
