day 17 파일 관리 작업
데이터베이스 파일: 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)
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.