編寫了一個名為learning_python.txt的文件,內容如下:
[root@centos7 tmp]# cat learning_python.txt In Python you can code;In Python you can learn object;In Python you can learn class.
要求:編寫一個程序,它讀取這個文件并打印三次。
1、第一次打印時讀取整個文件; 2、第二次打印時遍歷文件對象; 3、第三次打印時將各行存儲在一個列表中,再在with代碼塊外打印它們。1、第一次打印的代碼:
filename = 'learning_python.txt'with open(filename) as file_object: contents = file_object.read() print(contents.rstrip())
2、第二次打印的代碼:
filename = 'learning_python.txt'with open(filename) as file_object:#1 contents = file_object.read()#1 print(contents.rstrip()) for line in file_object: print(line.rstrip())
3、第三次打印的代碼:
filename = 'learning_python.txt'with open(filename) as file_object:#1 contents = file_object.read() 第一次打印,文件作為一個整體#1 print(contents.rstrip())#2 for line in file_object: 第二次打印,在with模塊內#2 print(line.rstrip()) lines = file_object.readlines()for line in lines: #第三次打印,在with模塊外 print(line.strip())
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對武林站長站的支持。如果你想了解更多相關內容請查看下面相關鏈接
新聞熱點
疑難解答