18_Python之文件读取
文件读取(Python语言实现) 1. 读取整个文件 read() fn = 'test.txt' file_obj = open ( fn , encoding = 'UTF-8' ) data = file_obj . read ( ) file_obj . close ( ) # 不关闭会对文件造成不必要的损害 print ( data ) 2. with 关键词 fn = 'test.txt' with open ( fn , encoding = 'utf-8' ) as file_obj : data = file_obj . read ( ) print ( data . rstrip ( ) ) # 输出时删除末端字符 3. 逐行读取文件 # 逐行读取文件内容 fn = 'test.txt' with open ( fn , encoding = 'utf-8' ) as file_obj : for line in file_obj : # 逐行读取文件到变量line print ( line ) # 有空行 # 逐行读取文件内容 fn = 'test.txt' with open ( fn , encoding = 'utf-8' ) as file_obj : for line in file_obj : # 逐行读取文件到变量line print (