首页 > 编程 > Python > 正文

Python 文件操作的详解及实例

2020-02-16 10:15:56
字体:
来源:转载
供稿:网友

Python 文件操作的详解及实例

一、文件操作

1、对文件操作流程

打开文件,得到文件句柄并赋值给一个变量 通过句柄对文件进行操作 关闭文件

现有文件如下:

昨夜寒蛩不住鸣。惊回千里梦,已三更。起来独自绕阶行。人悄悄,帘外月胧明。白首为功名,旧山松竹老,阻归程。欲将心事付瑶琴。知音少,弦断有谁听。f = open('小重山') #打开文件data=f.read()#获取文件内容f.close() #关闭文件

注意:if in the win,hello文件是utf8保存的,打开文件时open函数是通过操作系统打开的文件,而win操作系统默认的是gbk编码,所以直接打开会乱码,需要f=open(‘hello',encoding='utf8'),hello文件如果是gbk保存的,则直接打开即可。

2、文件打开模式  

Character Meaning

'r'    open for reading (default)'w'    open for writing, truncating the file first'x'    create a new file and open it for writing'a'    open for writing, appending to the end of the file if it exists'b'    binary mode't'    text mode (default)'+'    open a disk file for updating (reading and writing)'U'    universal newline mode (deprecated)

先介绍三种最基本的模式:

# f = open('小重山2','w') #打开文件# f = open('小重山2','a') #打开文件# f.write('莫等闲1/n')# f.write('白了少年头2/n')# f.write('空悲切!3')

3、文件具体操作

f = open('小重山') #打开文件# data1=f.read()#获取文件内容# data2=f.read()#获取文件内容## print(data1)# print('...',data2)# data=f.read(5)#获取文件内容# data=f.readline()# data=f.readline()# print(f.__iter__().__next__())# for i in range(5):#   print(f.readline())# data=f.readlines()# for line in f.readlines():#   print(line)# 问题来了:打印所有行,另外第3行后面加上:'end 3'# for index,line in enumerate(f.readlines()):#   if index==2:#     line=''.join([line.strip(),'end 3'])#   print(line.strip())#切记:以后我们一定都用下面这种# count=0# for line in f:#   if count==3:#     line=''.join([line.strip(),'end 3'])#   print(line.strip())#   count+=1# print(f.tell())# print(f.readline())# print(f.tell())#tell对于英文字符就是占一个,中文字符占三个,区分与read()的不同.# print(f.read(5))#一个中文占三个字符# print(f.tell())# f.seek(0)# print(f.read(6))#read后不管是中文字符还是英文字符,都统一算一个单位,read(6),此刻就读了6个中文字符#terminal上操作:f = open('小重山2','w')# f.write('hello /n')# f.flush()# f.write('world')# 应用:进度条# import time,sys# for i in range(30):#   sys.stdout.write("*")#   # sys.stdout.flush()#   time.sleep(0.1)# f = open('小重山2','w')# f.truncate()#全部截断# f.truncate(5)#全部截断# print(f.isatty())# print(f.seekable())# print(f.readable())f.close() #关闭文件            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表