python基础--文件操作

文件操作

目录:
1.基本概念
2.基本操作
3.例子_在磁盘修改文件

1.基本概念

三种基本的操作模式 r(只可读) w(只可写) a(追加)
流程:1 创建文件对象 2 调用文件方法进行操作 3 关闭文件
注意:必须要有f.close()操作,如果没有close操作数据会缓存,而不是存在磁盘。


2.基本操作
(1).read()
# f=open('小重山','r',encoding='utf8')
# data=f.read(5)
# print(data)
# f.close()

(2).write()
# f=open('小重山','w',encoding='utf8')
# f.write('\nhello world \n')
# f.write('alex')
# f.close()

(3).readline()
# f=open('小重山','w',encoding='utf8')
# a=f.readline()
# print(a)
# f.close()


(4).readlines()
# f=open('小重山','w',encoding='utf8')
#print(f.readlines())
# f.close()

(5).tell()
# f=open('小重山','r',encoding='utf8')
# print(f.tell())        #  取出光标位置,一个汉字3个字符
# print(f.read(2))
# print(f.tell())

(6).seek()
# f=open('小重山','r',encoding='utf8')
# f.seek(0)               # 移动光标到指定的位置
# print(f.read(4))
# f.close()

(7).flush()

#flush():同步把将数据从缓存转移到磁盘上去

(8).truncate()
# f=open('小重山','w',encoding='utf8')
# f.truncate(5)
# f.write('hello world')
# f.truncate(5)
# f.close()

(9)r+模式
# f=open('小重山','r+',encoding='utf8')
# print(f.tell())
# print(f.readline())
# f.close()

(10)with语句(防止open打开之后忘记关闭文件)
# with open('小重山', 'r',encoding='utf8') as f:
    # print(f.readline())
    # print(f.read())


3.例子_在磁盘修改文件

# f_read=open('file_1','r',encoding='utf8')
# f_write = open('file_2','w',encoding='utf8')
# number = 0
# for line in f_read:
#     number += 1
#     if number == 5:
#         line = ''.join([line.strip(),'需要添加的内容\n'])
#     f_write.write(line)
# f_read.close()
# f_write.close()

 

 
posted @ 2018-11-05 21:33  Kate_liu  阅读(171)  评论(0编辑  收藏  举报