編寫了乙個名為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 從檔案中讀取資料
學習python時,發現在使用with open pi digits.text as file object時,使用相對路徑,總是出現notfoundfileerror的錯誤,後來想到使用絕對路徑。書中提到的在linux環境中路徑使用的是斜槓 在windows環境中使用的是反斜槓 而經過實踐,發現只...
Python從檔案中讀取資料(2)
一 讀取檔案中各行的內容並儲存到乙個列表中 繼續用resource.txt 舉例 resource.txt my name is joker,i am 18years old,how about you?test.py 1 file name resource.txt 2 3with open fi...
Python從txt檔案中逐行讀取資料
coding utf 8 import os for line in open samples label val.txt print line line,end 後面跟 end 將忽略換行符 line samples images 3 3 5460e99f0ca9c410960571e02a0d2...