python文件学习

来源:互联网 发布:历年固定资产投资数据 编辑:程序博客网 时间:2024/04/28 10:58
all=open("w.txt").read()all_n=open("w.txt",'rb').read()print allprint all_nfile_object=open('w.txt')list_of_all_the_lines=file_object.readlines()print list_of_all_the_linesfile_object=open('w.txt')try:    all_the_text=file_object.read()finally:    file_object.close()    print all_the_text    

结果:

oh my god! what happen?so funny!oh my god! what happen?so funny!['oh my god! what happen?so funny!']oh my god! what happen?so funny!

当文件中包含换行的时候file_object=open('w.txt')list_of_all_the_lines=file_object.readlines()file_object=open('w.txt')list_of_all_the_lines1=file_object.read().split('\n')file_object=open('w.txt')list_of_all_the_lines2=[L.rstrip('\n') for L in file_object]print list_of_all_the_linesprint list_of_all_the_lines1print list_of_all_the_lines2

['oh my god! \n', 'what happen?\xa1\xa2\n', 'so funny!']['oh my god! ', 'what happen?\xa1\xa2', 'so funny!']['oh my god! ', 'what happen?\xa1\xa2', 'so funny!']