Python從文件中讀取數據的方法講解
更新時間:2019年02月14日 16:39:53 作者:zsx0728
今天小編就為大家分享一篇關于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())
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。如果你想了解更多相關內容請查看下面相關鏈接
相關文章
Python使用win32com模塊實現數據庫表結構自動生成word表格的方法
這篇文章主要介紹了Python使用win32com模塊實現數據庫表結構自動生成word表格的方法,結合實例形式分析了win32com模塊下載、連接mysql、查詢獲取表結構以及使用win32com生成word表格的相關操作技巧,需要的朋友可以參考下2018-07-07
PyTorch深度學習LSTM從input輸入到Linear輸出
這篇文章主要為大家介紹了PyTorch深度學習LSTM從input輸入到Linear輸出深入理解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-05-05

