python進階(7)--檔案與異常

Mrwhite86發表於2021-04-18

一、檔案讀取
二、檔案寫入
三、異常
四、儲存資料

---------------------------------------分割線:正文--------------------------------------------------------

一、檔案讀取

1、with語句

#採用idea的sources root的相對路徑
with open('..//data//pi_digits.txt') as file_object: contents = file_object.read()
#列印同時剔除空行
print(contents.rstrip())

檢視結果:

3.1415926535
  8979323846
  2643383279

2、絕對路徑

file_path='D:/Users/Mr.White/PycharmProjects/pythonProject/data/pi_digits.txt'
with open(file_path) as file_object:
    contents = file_object.read()
print(contents.rstrip())

檢視結果:

3.1415926535
  8979323846
  2643383279

3、for迴圈逐行讀取

with open('../data/pi_digits.txt') as file_object:
    for line in file_object:
        print(line.rstrip())

檢視結果:

3.1415926535
  8979323846
  2643383279

4、readline()方法,將檔案的內容儲存在列表內

with open('../data/pi_digits.txt') as file_object:
    lines=file_object.readlines()
for line in lines:
    print(line.rstrip())

檢視結果:

3.1415926535
  8979323846
  2643383279

優化程式碼,拼接字串讀取

with open('../data/pi_digits.txt') as file_object:
    lines=file_object.readlines()
pi_string=''
for line in lines:
    pi_string+=line.strip()
print(pi_string)
print(len(pi_string))

檢視結果:

3.141592653589793238462643383279
32

 

二、檔案寫入

1、with,覆蓋模式

file_name='../data/programming.txt'
with open(file_name,'w') as file_object:
    file_object.write("I love programming.")

檢視檔案(../data/programming.txt):

I love programming.

2、寫入多行

file_name='../data/programming.txt'
with open(file_name,'w') as file_object:
    file_object.write("I love programming.\n")
    file_object.write("i love creating new games.\n")

檢視檔案(../data/programming.txt):

I love programming.
i love creating new games.

3、with,附加模式

with open(file_name,'a') as file_object:
    file_object.write("I also love fing...\n")
    file_object.write("i love creating apps that...\n")

檢視檔案(../data/programming.txt):

I love programming.
i love creating new games.
I also love fing...
i love creating apps that...

 

三、異常

1、解決異常(ZeroDivisionError):try except

try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")

檢視結果:

You can't divide by zero!

2、解決異常(FileNotFoundError):try except

filename="testfile.txt"
try:
    with open(filename,encoding='utf-8') as f:
        contents=f.read()
except FileNotFoundError:
    print(f"sorry,the file {filename} does not exits.")

檢視結果:

sorry,the file testfile.txt does not exits.

3、異常時靜默處理:pass

try:
    print(5/0)
except ZeroDivisionError:
    pass

無顯示結果

 

四、儲存資料

1、寫入資料

import json
number=[2,3,5,7,11,13]
filename='../data/number.json'
with open(filename,'w') as f:
    json.dump(number,f)

檢視結果(number.json)

[2, 3, 5, 7, 11, 13]

2、讀取資料

filename='../data/number.json'
with open(filename) as f:
    numbers=json.load(f)
print(numbers)

檢視結果:

[2, 3, 5, 7, 11, 13]

3、json+input:儲存和讀取使用者輸入

username=input("What is your name?")
filename='username.json'
with open(filename,'w') as f:
    json.dump(username,f)
    print(f"We'll remember you when you come back,{username}!")
with open(filename) as f:
    username=json.load(f)
    print(f"Welcom back,{username}")

檢視結果:

What is your name?mike
We'll remember you when you come back,mike!
Welcom back,mike

4、封裝使用者輸入與儲存

def get_stored_username():
    """當沒有錯誤時讀取儲存的使用者名稱"""
    filename='username.json'
    try:
        with open(filename) as f:
            username=json.load(f)
    except FileNotFoundError:
        return None
    else:
        return username

def get_new_username():
    """驗證新使用者名稱"""
    username=input("What is your name?")
    filename='username.json'
    with open(filename,'w') as f:
        json.dump(username,f)
    return username

def greet_user():
    """greet the user by name"""
    username=get_stored_username()
    if username:
        print(f"Welcome back,{username}!")
    else:
        username=get_new_username()
        print(f"We will remember you when you come back,{username}!")

greet_user()

檢視執行結果:

Welcome back,mike!

 

相關文章