學習**
with open('pi_digits.txt') as file_object:
contents=file_object.read()
print(contents)
輸出結果
3.1415926535
8979323846
2643383279
filename='e:\code\python\pi_digits.txt'
with open(filename) as file_object:
for line in file_object:
print(line)
輸出結果
3.1415926535
8979323846
2643383279
filename='pi_digits.txt'
with open(filename) as file_object:
lines=file_object.readlines()
for line in lines:
print(line.rstrip())
pi_string=''
for line in lines:
pi_string+=line.rstrip()
print(pi_string)
print(len(pi_string))
輸出結果
3.141592653589793238462643383279
32
filename='programming.txt'
with open(filename,'w') as file_object:
file_object.write("i love programming.")
file_object.write("i love python")
在programming中的結果是
i love programming.i love python
要讓每個字串都單獨佔一行,可以使用\n
with open(filename,'a') as file_object:
file_object.write("i also love finding meaning in large datasets.\n")
try:
print(8/0)
except zerodivisionerror:
print("zerodivisionerror!!!")
輸出結果
zerodivisionerror!!!
print("else**塊")
print("divide.")
print("enter 'q' to quit!")
while true:
first_number=input("\nfirst number.")
if first_number=='q':
break
second_number=input("\nsecond number.")
try:
answer=int(first_number)/int(second_number)
except zerodivisionerror:
print("zerodivisionerror!")
else:
print(answer)
輸出結果
divide.
enter 'q' to quit!
first number.3
second number.1
3.0first number.3
second number.0
zerodivisionerror!
first number.q
filename='party.txt'
with open(filename) as f_obj:
contents=f_obj.read()
words=contents.split()
print(len(words))
輸出結果
154565
def count_words(filename):
try:
with open(filename) as f_obj:
contents=f_obj.read()
except filenotfounderror:
pass
else:
words=contents.split()
print(filename+" has about "+ str(len(words)))
filenames=['pi_digits.txt','alice.txt','party.txt']
for f in filenames:
count_words(f)
輸出結果
pi_digits.txt has about 3
party.txt has about 154565
import json
number=[2,3,5,7,11,13]
filename="number.json"
with open(filename,'w') as f_obj:
json.dump(number,f_obj)
with open(filename) as f_obj:
numbers=json.load(f_obj)
print(numbers)
username=input("what is your name?")
filename='username.json'
with open(filename,'w') as f:
json.dump(username,f)
with open(filename) as f:
username=json.load(f)
print(username)
輸出結果
what is your name?yang
yang
Python學習筆記 檔案和異常
1 從檔案中讀取資料 關鍵字with在不需要訪問檔案後自動將其關閉 open pi digits.txt 返回乙個表示檔案pi digits.txt的物件,並將該物件儲存在變數file object中 file object.read 讀取該檔案物件對應檔案的全部內容 contents.rstrip...
Python 檔案和異常
關鍵字with 在不再需要訪問檔案後將其關閉。我們使用方法read 讀取這個檔案的全部內容,並將其作為乙個長長的字串儲存在變數contents中.還可以將檔案在計算機中的準確位置告訴python,這樣就不用關心當前執行的程式儲存在什麼地方了。這稱為絕對檔案路徑 file path c users e...
Python檔案和異常
程式和執行時資料是在記憶體中駐留的,涉及到資料交換的地方,通常是磁碟 網路等,因此需要io介面。io程式設計中,stream 流 是乙個很重要的概念,可以把流想象成乙個水管,資料就是水管裡的水,但是只能單向流動。input stream就是資料從外面 磁碟 網路 流進記憶體,output strea...