day 17 파일 관리 작업

5795 단어
1. 데이터 로 컬 화 와 데이터 영구 화 - 파일 을 통 해 하 드 디스크 에 데 이 터 를 저장 합 니 다.
데이터베이스 파일: txt, json, plist, xml, png 파일, mp4, mp3 등
2. 파일 조작 - 파일 내용 조작
기본 단계: 파일 열기 -- > 작업 파일 (읽 기 / 쓰기) -- > 파일 닫 기
1) 파일 열기
open(file, mode,encoding = None)  -              ,            

file --    :         
        ./  --          
        ../  --               
        
mode  --    :     
            r --    ,         (      ),         
            w --          ,     
            a --          ,     
            rb/br --        ,          
            wb/bw --        ,           
            +   --            (  )

encoding   --        
               utf-8
                 :           、             

2. 파일 조작
    .read()  --           ,   
                                     (           )
    .seek(   ) --                (  )
def main():
    # 1.     
    f = open('test.txt','r',encoding= 'utf-8')
    print(f)
    result = f.read()
    print(result)



    # 2.     
    """
        .write(  )  --            ,        
    """
    f = open('test.txt','w',encoding= 'utf-8')
    wrt = f.write('     ')
    print(wrt)

    #     
    """
        .close()
    """
    f.close()

    # ======
    """
      :       ,                 ,       
                           ,                         
    """

if __name__ == '__main__':
    main()

바 이 너 리 파일 조작
rb  -                 (bytes)
wb   -                     

                    ,          ,          ;
                (  :  ,  )

바 이 너 리 데이터
                  ,                

1)         
bytes(str,encoding = 'utf-8')   

   .encode(    ) -  str.encode(encoding = 'utf-8')


2)           
str(     ,encoding = 'utf-8')

     .decode(    )

파일 상하 문
with open (파일 경로, 열기 방식, 인 코딩 방식) as 파일 대상: 작업 파일
파일 작업 이 완료 되면 자동 으로 닫 힙 니 다.
def main():
    with open('./files/test.txt', 'r', encoding='utf-8') as f1:
        print(f1.read())

    # 1.                
    f = open('./files/test.txt', 'rb')
    reslut = f.read()
    print(reslut, type(reslut))

    f = open('./files/test.txt', 'wb')
    f.write(bytes('bbb', encoding='utf-8'))

    # 2.      
    f1 = open('./files/luffy4.jpg', 'rb')
    reslut = f1.read()
    print(reslut, type(reslut))

    f2 = open('./files/aaa.jpg', 'wb')
    f2.write(reslut)



if __name__ == '__main__':
    main()

1. json 데이터
  json       json  

json  :   json        ,       json       

json       :
1、  (number) -         (     ),         。
2、   (string)  -              :"abcd","1234","  "             
3、  (boolean)  -  true/false
4、  (array)  -      python    ,[100,"abc",true,[1,2,3]]
5、  (dictionary)  -     python    ,{"a":10,"b":100,"c":true}
6、       -   null,      None

2. 제 이 슨 사용
1) 제 이 슨 데 이 터 를 분석 (제 이 슨 데 이 터 를 얻 은 후 제 이 슨 에서 원 하 는 것 을 분석) - 전단 개발 자 작업
2) 구조 json 데이터
# =====================1.json python(json    )============
 python       ,    json     : json 
a.  json     python  
json                python  
number                 int/float
string                 str,              
bool                   bool,true -> True   false ->  False
array                  list
dictionary             dict
                      null -> None

json.loads(   ,encoding = 'utf-8') -   json  
     :             json  (     ,      json  )

result = json.loads('"abc"',encoding='utf-8')
print(result,type(result))    # abc 

result = json.loads('100',encoding='utf-8')
print(result,type(result))    # 100 

result = json.loads('true',encoding='utf-8')
print(result,type(result))    # True 

result = json.loads('[10,23,"nsq",true]',encoding='utf-8')
print(result,type(result))    # [10, 23, 'nsq', True] 

result = json.loads('{"a": 100,"b": false}',encoding='utf-8')
print(result,type(result))    # {'a': 100, 'b': False} 

with open('jsontest.json','r',encoding='utf-8')as f:
    result = f.read()
    result_py = json.loads(result,encoding='utf-8')
    result1 = result_py['data']
    max_dict = max(result1, key=lambda x: int(x['favourite']))
    print(max_dict['name'],max_dict['text'],max_dict['favourite'])

# ======================2. python    json   ======================

"""
python            json  
int/float            number
bool                 True => true , False => false
str                  string  '' => ""
list,tuple           array
dict                 dictionary
                   None => null


json.dumps(python  )   ==》  python        json            
"""
result = json.dumps('abc')
print(result,type(result))
# ===================3.json     =====================
"""
json.load(    )   -                 python  
                                 json  

json.dump(python  ,    ) -   python     json  ,  (   )        

"""
with open('test.txt','r',encoding='utf-8')as f:
    result = json.load(f)
    print(type(result),result)

좋은 웹페이지 즐겨찾기