[ python ] 文件讀寫操作


 python3 文件讀寫操作

 1.  文件打開模式

 

2. 文件操作方法

 

 

文件讀寫與字符編碼

 

 

 python文件操作步驟示例

  以讀取為例,這樣一個文件:text.txt,  該文件的字符編碼為 utf-8

總有一天總有一年會發現
有人默默的陪在你的身邊
也許 我不該在你的世界
當你收到情書
也代表我已經走遠

 

1. 基本實現

f = open('text.txt', 'r', encoding='utf-8')
print(f.read())
f.close()

 

2. 中級實現

在基本實現的的基礎上,可能要考慮到一些可能出現的意外因素。因為文件讀寫時都有可能產生IO錯誤(IOError),一旦出錯,后面包括 f.close() 在內的所有代碼都不會執行了,因此我們要保證文件無論如何都應該關閉。

f = ''  # 全局要申明下 f 變量,不然 f.close() 會報黃
try:
    f = open('text.txt', 'r', encoding='utf-8')
    print(f.read())
finally:
    if f:
        f.close()

 在上面的代碼中,就是 try 中的代碼出現了報錯,依然會執行 finally 中的代碼,即文件關閉操作被執行。

 

3. 最佳實踐

為了避免忘記或者為了避免每次都要手動關閉文件,且過多的代碼量,我們可以使用 with 語句,with 語句會在其代碼塊執行完畢之后自動關閉文件。

with open('text.txt', 'r', encoding='utf-8') as f:
    print(f.read())
print(f.closed) # 通過 closed 獲取文件是否關閉,True關閉,False未關閉

# 執行結果:
# 總有一天總有一年會發現
# 有人默默的陪在你的身邊
# 也許 我不該在你的世界
# 當你收到情書
# 也代表我已經走遠
# True

 

 

用戶注冊登錄實例

要求:

  1. 用戶可注冊不同的賬戶,並將用戶信息保存到本地文件中;

  2. 下次登錄,注冊過的用戶都可實現登錄

 

代碼:

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author: hkey
import os


def file_oper(file, mode, *args):
    if mode == 'r':
        list_user = []
        with open(file, mode) as f:
            for line in f:
                list_user.append(line.strip())
            return list_user
    elif mode == 'a+':
        data = args[0]
        with open(file, mode) as f:
            f.write(data)


class User(object):
    def __init__(self, name, passwd):
        self.name = name
        self.passwd = passwd
        self.file = 'user.db'

    def regist(self):
        data = '%s|%s\n' % (self.name, self.passwd)
        file_oper(self.file, 'a+', data)
        if os.path.isfile('user.db'):
            print('\033[32;1m注冊成功.\033[0m')

    def login(self):
        list_user = file_oper(self.file, 'r')
        print('list_user:', list_user)
        user_info = '%s|%s' % (self.name, self.passwd)
        if user_info in list_user:
            print('\033[32;1m登錄成功.\033[0m')
        else:
            print('\033[31;1m登錄失敗.\033[0m')


def start():
    while True:
        print('1. 注冊\n'
              '2. 登錄\n'
              '3. 退出')

        choice = input('\033[34;1m>>>\033[0m').strip()
        if choice == '1':
            username = input('\033[34;1musername:\033[0m').strip()
            password = input('\033[34;1mpassword:\033[0m').strip()
            user = User(username, password)
            user.regist()
        elif choice == '2':
            username = input('\033[34;1musername:\033[0m').strip()
            password = input('\033[34;1mpassword:\033[0m').strip()
            user = User(username, password)
            user.login()
        elif choice == '3':
            break
        else:
            print('\033[31;1m錯誤:輸入序號錯誤。\033[0m')


if __name__ == '__main__':
    start()
user_info.py

 

2019-12-23 再次編寫:

from os.path import isfile

class User:
    def __init__(self, username, passwd, file_info):
        self.user = username
        self.pwd = passwd
        self.file_db = file_info

    @staticmethod
    def file_oper(file, mode, *args):
        if mode == 'a+':
            data = args[0]
            with open(file, mode) as f:
                f.write(data)
        elif mode == 'r':
            with open(file, mode) as f:
                data = f.read()
                return data


    def regist(self):
        list_user = []
        if isfile(self.file_db):
            with open(self.file_db, 'r') as f:
                for line in f:
                    username = line.strip().split(':')[0]
                    list_user.append(username)
        if self.user not in list_user:
            try:
                with open(self.file_db, 'a+') as f:
                    user_info = '%s:%s\n' %(self.user, self.pwd)
                    f.write(user_info)
                print('\033[32;1m注冊成功。\033[0m')
            except Exception as e:
                print('Error: ', e)
        else:
            print('\033[31;1m該用戶已存在.\033[0m')


    def login(self):
        list_user = []
        u_list = '%s:%s' %(self.user, self.pwd)
        with open(self.file_db, 'r') as f:
            for line in f:
                list_user.append(line.strip())
        if u_list in list_user:
            print('\033[32;1m登錄成功.\033[0m')
        else:
            print('\033[31;1m用戶名或密碼錯誤.\033[0m')



def start():
    while True:
        print('1. 注冊\n'
              '2. 登錄\n'
              '3. 退出')
        choice = input('>>>').strip()
        if choice.isdigit() and 0 < int(choice) < 4:
            if choice == '1':
                username = input('用戶名:').strip()
                passwd = input('密碼:').strip()
                user = User(username, passwd, 'user.db')
                user.regist()
            elif choice == '2':
                username = input('用戶名:').strip()
                passwd = input('密碼:').strip()
                user = User(username, passwd, 'user.db')
                user.login()
            elif choice == '3':
                break
        else:
            print('輸入錯誤.')


if __name__ == '__main__':
    start()
user_info.py

 

 

更多參考鏈接:https://www.cnblogs.com/yyds/p/6186621.html

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM