Python三种读取txt文件方式

简单介绍

1.按行读取方式readline()

readline()每次读取文件中的一行,需要使用永真表达式循环读取文件。但当文件指针移动到文件的末尾时,依然使用readline()读取文件将出现错误。因此程序中需要添加1个判断语句,判断文件指针是否移动到文件的尾部,并且通过该语句中断循环。

2.多行读取方式readlines()

使用readlines()读取文件,需要通过循环访问readlines()返回列表中的元素。函数readlines()可一次性读取文件中多行数据。

3.一次性读取方式read()读取文件最简单的方法是使用read(),read()将从文件中一次性读出所有内容,并赋值给1个字符串变量。

代码:

# -*- coding: utf-8 -*-

file =open('/Users/april_chou/Desktop/WorkSpace/Selenium/seleniumTest/test.txt','r')

context = file.read()

print('read格式:')

print(context)

file.close()

print()

file =open('/Users/april_chou/Desktop/WorkSpace/Selenium/seleniumTest/test.txt','r')

context = file.readlines()

contextLines =''

for i in context:

    contextLines = contextLines + i

print('readlines格式:')

print(contextLines)

file.close()

print()

file =open('/Users/april_chou/Desktop/WorkSpace/Selenium/seleniumTest/test.txt','r')

contextLines =''

while True:

    context = file.readline()

    contextLines = contextLines + context

    if len(context) ==0:

    break

print('readline格式:')

print(contextLines)

file.close()

结果:

read格式:

hello world

hello China

readlines格式:

hello world

hello China

readline格式:

hello world

hello China

原文地址:https://www.cnblogs.com/April-Chou-HelloWorld/p/8833874.html