""" 1、打开文件: open() ,参数是文件的名称 """ # 读取整个文件 with open('china.txt') as file_object: contents = file_object.read() print(contents) # rstrip() 去除文本末尾空行 print(contents.rstrip()) print('==================') # 逐行读取 filename = 'china.txt' with open(filename) as file_object: print(file_object) for line in file_object: # 文件中的换行符也会读取出来 print(line) print('==================') # 创建一个包含文件各行内容的列表 # readlines() 表示读取文件中的每一行并将其储存在列表中 with open(filename) as file_object: lines = file_object.readlines() for line in lines: print(line.rstrip()) print('==================') # 简单实用文件的内容 with open(filename) as file_object: lines = file_object.readlines() c_str = '' for line in lines: c_str += line.rstrip() print(c_str) print(len(c_str))