第十章文件和异常

#1.
#A:使用关键字with后,会在不需要访问文件后将其关闭
#B:open(),默认以"r"的形式打开文件,close()分别用于关闭文件
#C:读取文件的方法:read()默认读取整个文件,可以指定读取字节。readline()读取一行,readlines()按行读取后存入列表,当传入读取字节数目后,则读取的内容可能是行的一部分
#D:python3将文件当做一个可迭代的类型,此方法比较好
#E:seek()设置开始读的位置, tell()得到当前开始读取位置

#Test.txt内容是12
22
32
with open("Test.txt") as pFile:
    buffFile = pFile.read()     #buffFile = '12
22
32'
with open("Test.txt", "rb") as pFile:
    buffFile = pFile.read()     #buffFile = b'12
22
32'
with open("Test.txt", "rb") as pFile:
    buffFile = pFile.read(4)    #buffFile = b'12


pFile = open("Test.txt")
buffFile = pFile.readline()     #buffFile = '12
'
pFile.close()

buffFile = ""
with open("Test.txt") as pFile:
    buffFile = pFile.readlines()#buffFile = ['12
', '22
', '32
']

pFile = open("Test.txt")
buffFile = ''
for line in pFile:              #python3将文件当做一个可迭代的类型
    buffFile += line            #buffFile = '12
22
32'
pFile.close()

pFile = open("Test.txt")
pFile.seek(1)
value = pFile.tell()            #value = 1
buffFile = pFile.read()         #buffFile = '2
22
32'
pFile.close()

#2.
#A:open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True)
#B:在Python3,可以通过open函数的newline参数来控制Universal new line mode:读取时候,不指定newline,则默认开启Universal new line mode,所有
, 
, or 
被默认转换为

#  写入时,不指定newline,则换行符为各系统默认的换行符(
, 
, or 
),指定为newline='
',则都替换为
(相当于Universal new line mode);
#  不论读或者写时,newline=''都表示不转换。

#Test.dat内容:'1', 0x0d, '2', 0x0d, 0x0a, '3', 0x0a, '4'
with open("Test.dat") as pFile:
    buffFile = pFile.read()     #buffFile = '1
2
3
4'
with open("Test.dat", "rb") as pFile:
    buffFile = pFile.read()     #buffFile = b'1
2
3
4'
with open("Test.dat", "r", newline = "") as pFile:
    buffFile = pFile.read()     #buffFile = '1
2
3
4'

#TestWithNull.dat内容:'1', 0x0d, '2', 0x0d, 0x0a, '3', 0x0a, '4', 0, 0
with open("TestWithNull.dat", "rb") as pFile:
    buffFile = pFile.read()     #buffFile = b'1
2
3
4x00x00'

#3.
#A:write()用于写入文件
#B:writelines()用于写入多行
with open("Write.txt", "wb") as pFile:
    pFile.write(b'1
2
3
4x00x00')    #文件中内容:0x31 0x0d 0x32 0x0d 0x0a 0x33 0x0a 0x34 0x00 0x00
with open("Write.txt", "w") as pFile:
    pFile.write('1
2
3
4x00x00')     #文件内容:0x31 0x0d 0x32 0x0d 0x0d 0x0a 0x33 0x0d 0x0a 0x34 0x00 0x00
with open("Write.txt", "w", newline = '') as pFile:
    pFile.write('1
2
3
4x00x00')     #文件内容:0x31 0x0d 0x32 0x0d 0x0a 0x33 0x0a 0x34 0x00 0x00

with open("Write.txt", "w") as pFile:
#    pFile.write(b'1
2
3
4x00x00')   #运行时候报错:must be str, not bytes
    pass

value = ["123", '456']
with open("Write.txt", "w") as pFile:
#    pFile.write(value)                     #运行时候报错:must be str, not list
    pass

value = ["123", '456']
with open("Write.txt", "w") as pFile:
    pFile.writelines(value)                 #文件内容:123456

#4.
#A:python使用异常来管理程序执行期间发生的错误。每当发送错误的时候,都会创建一个异常对象,若编写了处理该异常的代码,则程序会继续运行,否则会报错
#B:split()根据字符串创建一个单词列表
#C:pass语句充当占位符,表示当前不做任何事

#value = 1 / 0                              #此处会出现异常
try:
    value = 1 / 0
except ZeroDivisionError:
    print("Error")                          #Error
else:
    print('Not Error')

try:
    value = 1 / 1
except ZeroDivisionError:
    print("Error")
else:
    print('Not Error')                      #Not error

try:
    pFile = open("NotExitFile.dat")
except FileNotFoundError:
    print('File Not Find')                  #File Not Find
else:
    pFile.close()      
    
value = 'hello world bad world'
result0 = value.split()                     #result0 = ['hello', 'world', 'bad', 'world']
result1 = set(result0)                      #result1 = {'world', 'bad', 'hello'}

#5.
#A:loads()将字符串解析为json格式, dumps将json格式解析为字符串
#B:load()从文件中读取内容并解析为json格式,dump()将json解析成的字符串写入文件
import json
value = '{"people" : [{"A" : 90}, {"B" : 80}, {"C" : 70}],"data" : 10}'
jsonValue = json.loads(value)               #jsonValue = {"people" : [{"A" : 90}, {"B" : 80}, {"C" : 70}],"data" : 10}
data = jsonValue['people']                  #data = [{'A': 90}, {'B': 80}, {'C': 70}]
data = jsonValue['data']                    #data = 10
jsonValue['Test'] = 'szn';                  #jsonValue = {"people" : [{"A" : 90}, {"B" : 80}, {"C" : 70}],"data" : 10, "Test": "szn"}

value = {"people" : [{"A" : 90}, {"B" : 80}, {"C" : 70}],"data" : 10};
json_str = json.dumps(value)                #json_str = '{"data": 10, "people": [{"A": 90}, {"B": 80}, {"C": 70}]}'

with open("JsonFile.json", "w") as pFile:
    json.dump(value, pFile)                 #文件内容:{"data": 10, "people": [{"A": 90}, {"B": 80}, {"C": 70}]}

with open("JsonFile.json") as pFile:
    buff = json.load(pFile)                 #buff = '{"data": 10, "people": [{"A": 90}, {"B": 80}, {"C": 70}]}'

value = {1:2, '1':2}                        #value = {1: 2, '1': 2}
json_str = json.dumps(value)                #json_str = '{"1": 2, "1": 2}'
Test = json.loads(json_str)                 #Test = {'1': 2}

  

原文地址:https://www.cnblogs.com/szn409/p/6517096.html