Python從文件中讀取數據的方法講解

今天小編就爲大家分享一篇關於Python從文件中讀取數據的方法講解,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧

編寫了一個名爲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())

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對神馬文庫的支持。如果你想了解更多相關內容請查看下面相關鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章