Pythonでファイル操作ヘルパークラスを実装する方法

王林
リリース: 2023-05-05 22:19:14
転載
1732 人が閲覧しました

1. ビジネス要件

ビジネス開発に Python を使用する場合、その後のデータ分析と表示を容易にするために、一部のデータをローカル ファイル ストレージに保存する必要があります。

2. 要件分析

要件を検討すると、データはローカル ファイルとして保存する必要があると結論付けることができます (これはファイルに関係する操作です)。ファイル操作は基本的な内容であり、よく使用されるファイルを直接使用できます。ファイル操作はファイルにカプセル化されており、後で直接呼び出すことができます。

3. 実装方法

3.1. Python ファイルヘルプクラス

#文件操作
 
import pickle
 
#读取文件的所有内容(返回字符串)
def ReadFileAllInfoAsStr(filePathAndName):
    try:
        with open(filePathAndName) as fileObj:
            fileInfos=fileObj.read()
    except FileNotFoundError:
        msg="很抱歉,文件【"+filePathAndName+"】不存在"
        print(msg)
    else:
        return fileInfos
 
#读取文件的所有内容(返回列表)
def ReadFileAllInfoAsList(filePathAndName):
    try:
        with open(filePathAndName) as fileObj:
            fileInfos=fileObj.readlines()
    except FileNotFoundError:
        msg="很抱歉,文件【"+filePathAndName+"】不存在"
        print(msg)
    else:
        return fileInfos
 
#写入信息到文件(覆盖原有内容)
def WriteInfo(needWriteInfo,filePathAndName):
    try:
        with open(filePathAndName,'wb') as fileObj:
            tmpBytes = bytes(needWriteInfo,'utf8')
            fileObj.write(tmpBytes)
    except Exception as e:
        print(e)
 
    
#追加信息到文件中
def AppedInfo(needWriteInfo,filePathAndName):
    try:
        with open(filePathAndName,'ab') as fileObj:
            tmpBytes = bytes('\n'+needWriteInfo,'utf8')
            fileObj.write(tmpBytes)
    except Exception as e:
        print(e)
 
 
#写入对象到文件
def WriteObj(needWriteInfo,filePathAndName):
    try:
       with open(filePathAndName,'wb') as fileObj:
           pickle.dump(needWriteInfo,fileObj)
    except Exception as e:
        print(e)
 
#读取文件内容
def ReadObj(filePathAndName):
    try:
       with open(filePathAndName,'rb') as fileObj:
        tmpObj = pickle.load(fileObj)
    except Exception as e:
        print(e)
    else:
        return tmpObj
    
 
import json
import codecs
 
#写入信息为json文件
def WritInfoAsJson(needWriteInfo,filePathAndName):
    try:
        with codecs.open(filePathAndName,'wb',encoding='utf-8') as fileObj:
            json.dump(needWriteInfo,fileObj)
    except Exception as e:
        print(e)
 
#读取json文件信息
def ReadInfoToJson(filePathAndName):
    try:
        with codecs.open(filePathAndName,'rb',encoding='utf-8') as fileObj:
            tmpJson=json.load(fileObj)
    except Exception as e:
        print(e)
    else:
        return tmpJson
ログイン後にコピー

3.2. Python ファイルヘルプクラス

import FileOPC
 
print('\n写入信息到文件中')
filePathAndName2='file/test.txt'
tmpstr="测试写入内容abcdefg"
FileOPC.WriteInfo(tmpstr,filePathAndName2)
 
print('\n将字符串转为字节1')
tmpbytes1=str.encode('测试写入内容','utf-8')
print(tmpbytes1)
print('\n将字符串转为字节2')
tmpbytes2=bytes('测试写入内容','utf-8')
print(tmpbytes2)
 
print('\n追加信息到文件中')
FileOPC.AppedInfo('追加信息123',filePathAndName2)
FileOPC.AppedInfo('测试追加信息456',filePathAndName2)
 
print('\n切分字符串')
splitStr="Alice in wonderlan 切割字符串,1,2,3,45,6"
tmpSplit = splitStr.split(',')
print(tmpSplit)
 
print('\n写入对象信息到文件')
filePathAndName3='file/test2.txt'
FileOPC.WriteObj('测试写入对象信息112254799abcadshofdsaujfoduasfoj',filePathAndName3)
 
print('\n读取文件对象')
tmpObj = FileOPC.ReadObj(filePathAndName3)
print(tmpObj)
 
import json
print('\n写入信息保存为Json文件')
filePathAndName4='file/testJson.json'
jsonDatas={"101001":[1,3,5,7,9],"101009":["张三","李四",'王五']}
#jsonDatas=[2,3,5,7,11,13]
 
FileOPC.WritInfoAsJson(jsonDatas,filePathAndName4)
 
print('\n读取Json文件信息')
tmpJson=FileOPC.ReadInfoToJson(filePathAndName4)
print(tmpJson)
ログイン後にコピー

3.3. 実行結果サンプル

Pythonでファイル操作ヘルパークラスを実装する方法

Pythonでファイル操作ヘルパークラスを実装する方法

以上がPythonでファイル操作ヘルパークラスを実装する方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

関連ラベル:
ソース:yisu.com
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
最新の問題
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート
私たちについて 免責事項 Sitemap
PHP中国語ウェブサイト:福祉オンライン PHP トレーニング,PHP 学習者の迅速な成長を支援します!