Python学习笔记——文件和异常

本章学习了文件的读取、写入和异常处理,还有在文件中存储数据
文件的读取和写入使用 with open('文件路径\文件名') as file 语句

open('文件路径\文件名')视作只读模式,写入模式需要使用open('文件路径\文件名','w'),附加模式使用open('文件路径\文件名','a'),附加模式下不可修改文件,但是可以添加内容
一般不使用close()来关闭文件,而是由python决定何时关闭文件,以防止错误

异常处理使用try except 语句实现抛出错误后的处理,非常简单实用
在python的模块中有json模块,可以使用模块中的dump()和load()函数实现数据的共享式存储和使用

以下是部分练习题的实现:

#10-1 读取文件
with open('10_1.txt') as file:
    contents=file.read()
    print(contents)
with open('10_1.txt') as file:
    for line in file:
        print(line.strip())
with open('10_1.txt') as file:
    lines=file.readlines()
    for line in lines:
        print(line.strip())
print('\n')

#10-2 用replace()函数替换字符串中特点字符
text=''
for line in lines:
    text+=line.strip()
    text+='\n'
print(text.replace("Python","C"))
print('\n')

#10-4 写入文件
with open('10_4.txt','w') as file2:
    while 1:
        name=input('Plz enter your name(enter 0 to exit):')
        if name=='0':
            break
        else:
            print('Hi,',name,'.')
            file2.write(name+'\n')
with open('10_4.txt','r') as file2:
    contents2=file2.read()
    print(contents2)
print('\n')

#10-7  ValueError
while 1:
    try:
        num1=int(input('Plz enter a number:'))
    except ValueError:  #这里用的是ValueError,课本所说的TypeError有误
        print('Plz enter number but not word!')
        continue
    try:
        num2=int(input('Plz enter another number:'))
    except ValueError:
        print('Plz enter number but not word!')
        continue
    print(num1+num2)
    print('Enter 1 to continue:')
    if input()!='1': break
print('\n')

#10-12
import json
def getNum():
    try:
        with open('10_12.txt') as file3:
            number=json.load(file3)
    except FileNotFoundError:
        return None
    else:
        return number

def setNum():
    try:
        number=int(input('Plz enter your favorite number:'))
    except ValueError:
        print('You did not enter a number!')
    else:
        with open('10_12.txt','w') as file3:
            json.dump(number,file3)
            print('We have save your number!')

def checkNum():
    num=getNum()
    if num:
        print('Your favorite number is ',end='')
        print(num)
    else:
        setNum()

checkNum()
checkNum()
print('\n')
2018/4/8

你可能感兴趣的:(Python学习笔记——文件和异常)