filename ='text.txt'# 把要读取的文件名存储在变量filename中withopen(filename)as file_object:#打开文件,并将其存储在变量file_object中
contents = file_object.read()# **方法read(),表示读取文件的全部内容**,并将其存储在变量contents中print('The content in the text file is: ')print(contents)// 输出结果为:
The content in the text fileis:
You are so kind
But I really do not need your help
Thanks a lot
2、逐行读取文件
filename ='text.txt'withopen(filename)as file_object:for line in file_object:# 通过对文件对象执行循环来遍历文件中的每一行print(line)// 输出结果为:
You are so kind
But I really do not need your help
Thanks a lot
3、将文件中的每一行存储到列表中,并在with代码块外使用
filename ='text.txt'withopen(filename)as file_object:
lines = file_object.readlines()#方法readlines()从文件中读取每一行,并将其存储在一个列表中print(lines)# 打印列表for line in lines:# 读取列表中的每一个元素print(line.strip())# 把每个行前面和后面的空格删除,用strip()方法// 输出结果为:
['You are so kind\n','But I really do not need your help\n','Thanks a lot']
You are so kind
But I really do not need your help
Thanks a lot
4、使用文件中的内容
filename ='text.txt'withopen(filename)as file_object:
lines = file_object.readlines()
text_string =''# 创建一个空的字符串,用于存储文件中的值for line in lines:
text_string += line.strip()# 使用一个循环将各行都加入到text_string中,并删除每行末尾的换行符。print(text_string)# 打印文件print(len(text_string))# 计算字符串长度//输出结果为:
123454645363374056710475017402048502405240