【课程11】文件的读写

【文件的打开方式】

# fo = open('D:/py/file1.txt')
# N = fo.read()
#文件的打开,读模式(文件必须要存在)
#file_object = open(file_name ,access_mode = 'r')
# file_name 文件路径,分为相对路径(D:/file)和绝对路径(./file),(../返回根目录)
# access_mode = 'r' 读(定义时等于号指定的值,缺省参数)、写、读+写
fileDir = 'D:/py/file1.txt'
# fo = open(fileDir,'rb')
#文件指针,文件队形的tell方法获取文件指针的位置
# print(fo.tell())#针对字符串的方法
# print(fo.read(2))#读两位,读完后指针变更位置
#seek方法,移动指针方法
# fo.seek(2,0)#从偶开始数移动2个光标
'''
0模式-绝对位置0,r模式返回字符串
1模式-当前位置,需要rb模式(open(fileDir,'rb'))二进制(bin)
2模式-从尾部开始算
'''
# print(fo.read(2))
# fo.seek(-2,2)#后面往前读
# print(fo.read(2))
# fo.seek(2,1)
# print(fo.read())#读所有的
# print(fo.tell())
#readline,每行作为list的一个元素,行尾是贷 的
# print(fo.readline())#返回字符串——不需要处理每行数据
# lines = fo.readlines()#返回列表——需要处理每行
# print(lines[0])
# print(fo.read().splitlines())#全部读取--按/切割换行符
# fo.close()#文件关闭

【文件的读写】

str1 = 'ajdfajkd'
fo = open(fileDir,'w')#文件存在清空,文件不存在新建
fo.write(str1+' ')#清空写入新内容,可输入后换行
fo.flush()#保存
# fo.close()#文件关闭,会自动保存写入内容

#a模式,写模式,格式和w一样(a写入不清空,w模式写入会清空)
#r+(可判断文件是否存在)、w+、a+(读写模式)
#with open方式
with open(fileDir) as fo , open(fileDir) as fo:
print('文件操作')
#优点,不能写关闭文件close()
#可以对多个文件进行操作
若有错误或建议,敬请联系勘正! 创建者:万骨枯 联系QQ:964942913 地址:四川成都
原文地址:https://www.cnblogs.com/wanguku/p/10261875.html