美文网首页编程
Python基础学习4

Python基础学习4

作者: ericblue | 来源:发表于2018-11-21 12:56 被阅读0次

文件内建函数和方法
open() 打开文件
read() 输入
readline() 输入一行
seek() 文件内移动
write() 输出
close() 关闭文件
下面文件操作实践:

# 将小说的主要人物记录在文件中
file1 = open('name.txt','w',encoding='utf-8')
file1.write("诸葛亮")
file1.close()

file2 = open('name.txt','r',encoding='utf-8')
print(file2.read())
file2.close()

#新增写入操作
file3 = open('name.txt','a',encoding='utf-8')
file3.write('刘备')
file3.close()

file4 = open('name.txt','r',encoding='utf-8')
print (file4.readline())

#逐行处理
file5 = open('name.txt','r',encoding='utf-8')
for line in file5.readlines():
    print(line)
    print('=====')


file6 = open('name.txt','r',encoding='utf-8')
print('当前文件指针的位置 %s' %file6.tell())
print ( '当前读取到了一个字符,字符的内容是 %s' %file6.read(1))#read(1) 表示只读取一个字符
print('当前文件指针的位置 %s' %file6.tell())#mac系统默认在文本文件写入一个汉字会占用三个位置


# 第一个参数代表偏移位置,第二个参数  0 表示从文件开头偏移  1表示从当前位置偏移,   2 从文件结尾
file6.seek(5,0)
print('我们进行了seek操作')
print('当前文件指针的位置 %s' %file6.tell())
print ( '当前读取到了一个字符,字符的内容是 %s' %file6.read(1))
print('当前文件指针的位置 %s' %file6.tell())
file6.close()

异常检测和处理:
异常是在出现错误时采用正常控制流以外的动作。
异常处理的一般流程是: 检测到错误,引发异常;对异常进行捕获的操作。
try:
<监控异常>
except Exception[, reason]:
<异常处理代码>
finally:
<无论异常是否发生都执行>
下面观察出错提示,并进行捕获处理:

i = j


print())


a='123'
print(a[3])

d = {'a':1 ,'b':2}
print(d['c'])


year = int(input('input year:'))

try:
    year = int(input('input year:'))
except ValueError:
    print('年份要输入数字')

a=123
a.append()

except (ValueError, AttributeError, KeyError)


try:
    print(1/'a')
except Exception as e:
    print(' %s' %e)

try:
    raise NameError('helloError')
except NameError:
    print('my custom error')


try:
    a = open('name.txt')
except Exception as e:
    print(e)

finally:
    a.close()

相关文章

网友评论

    本文标题:Python基础学习4

    本文链接:https://www.haomeiwen.com/subject/numwfqtx.html