如何在Python中读取文本文件?
文本文件是包含简单文本的文件。Python 提供内置函数来读取、创建和写入文本文件。我们将讨论如何在 Python 中读取文本文件。
在 Python 中读取文本文件有三种方法:
read() − 此方法读取整个文件并返回包含文件所有内容的单个字符串。
readline() − 此方法从文件中读取一行并将其作为字符串返回。
readlines() − 此方法读取所有行并将其作为字符串列表返回。
在Python中读取文件
假设有一个名为“myfile.txt”的文本文件。我们需要以读取模式打开该文件。“r”指定读取模式。可以使用 open() 打开文件。传递的两个参数是文件名和需要打开文件的模式。
示例
file=open("myfile.txt","r")
print("read function: ")
print(file.read())
print()
file.seek(0) #Take the cursor back to begining of the file since the read() takes the cursor to the end of file
print("readline function:")
print(file.readline())
print()
file.seek(0) #Take the cursor back to beginning of file
print("readlines function:")
print(file.readlines())
file.close()输出
read function: This is an article on reading text files in Python. Python has inbuilt functions to read a text file. We can read files in three different ways. Create a text file which you will read later. readline function: This is an article on reading text files in Python. readlines function: ['This is an article on reading text files in Python.\n', 'Python has inbuilt functions to read a text file.\n', 'We can read files in three different ways.\n', 'Create a text file which you will read later.']
从输出中可以清楚地看出:
read() 函数读取并返回整个文件。
readline() 函数读取并仅返回一行。
readlines() 函数读取并返回所有行作为字符串列表。
广告
数据结构
网络
关系数据库管理系统(RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP