欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python從文件中讀取數(shù)據(jù)的方法講解

 更新時間:2019年02月14日 16:39:53   作者:zsx0728  
今天小編就為大家分享一篇關(guān)于Python從文件中讀取數(shù)據(jù)的方法講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧

編寫了一個名為learning_python.txt的文件,內(nèi)容如下:

[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模塊內(nèi)
#2    print(line.rstrip())
  lines = file_object.readlines()
for line in lines: #第三次打印,在with模塊外
  print(line.strip())

總結(jié)

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

相關(guān)文章

最新評論