with open(file_path, 'r') as f: line = f.readline() # 读取一行 lines = f.readlines() #读取所有行(返回一个列表,一行作为一个元素) content = f.read() # 读取所有行(返回一个字符串,内容为整个文本)
第2个回答 2024-05-15
Python读取文本文件的步骤非常简单。以下是三种最常用读取txt文件的方法: 1、使用open()函数 #打开文件,mode参数指定打开方式('r'表示只读) with open("file.txt","r")as f: #读取文件内容 text=f.read() 2、使用for循环 with open("file.txt","r")as f: #按行读取文件内容 for line in f: #对每一行内容进行处理 print(line) 3、使用readlines()方法 with open("file.txt","r")as f: #读取文件内容到一个列表中,每行为一个元素 lines=f.readlines() 4、示例代码 #使用open()函数读取整个文件: with open("password.txt","r")as f: passwords=f.read() print(passwords) #使用for循环按行读取文件 with open("data.txt","r")as f: for line in f: print(line.strip()) #使用readlines()方法读取文件到列表: with open("employees.txt","r")as f: employees=f.readlines() for employee in employees: print(employee.strip())