设为首页 收藏本站
查看: 718|回复: 0

[经验分享] Python 学习入门(12)—— 文件

[复制链接]

尚未签到

发表于 2017-4-28 06:03:09 | 显示全部楼层 |阅读模式
  python进行文件读写的函数是open或file:f = open(filename, mode)


  模式
  描述
  r
  以读方式打开文件,可读取文件信息。
  w
  以写方式打开文件,可向文件写入信息。如文件存在,则清空该文件,再写入新内容
  a
以追加模式打开文件(即一打开文件,文件指针自动移到文件末尾),如果文件不存在则创建
  r+
  以读写方式打开文件,可对文件进行读和写操作。
  w+
  消除文件内容,然后以读写方式打开文件。
  a+
  以读写方式打开文件,并把文件指针移到文件尾。
  b
  以二进制模式打开文件,而不是以文本模式。该模式只对Windows或Dos有效,类Unix的文件是用二进制模式进行操作的。

  
  
  Table文件对象方法

  方法
  描述
  f.open(file, mode)
  打开文件,file是文件名,mode是打开模式(r/r+,w/w+, a/a+, b)
  f.close()
  关闭文件,记住用open()打开文件后一定要记得关闭它,否则会占用系统的可打开文件句柄数。
  f.fileno()
  获得文件描述符,是一个数字
  f.flush()
  刷新输出缓存
  f.isatty()
  如果文件是一个交互终端,则返回True,否则返回False。
  f.read([count])
  读出文件,如果有count,则读出count个字节。
  f.readline()
  读出一行信息。
  f.readlines()
  读出所有行,也就是读出整个文件的信息。
  f.seek(offset[,where])
  把文件指针移动到相对于where的offset位置。where为0表示文件开始处,这是默认值;1表示当前位置;2表示文件结尾。
  f.tell()
  获得文件指针位置。
  f.truncate([size])
  截取文件,使文件的大小为size。
  f.write(string)
  把string字符串写入文件。
  f.writelines(list)
  把list中的字符串一行一行地写入文件,是连续写入文件,没有换行。



  
  
  读写文件

#/usr/bin/python
#
# ithomer in 2013

filename = "test_file.txt"
def write_file():
f = open(filename, 'w')
f.write('hello ithomer')
f.write('\n')
f.write('my blog: http://blog.ithomer.net')
f.write('\n')
f.write('this is the end')
f.write('\n')
f.close()
def read_file():
f = open(filename, 'r')
line = f.readline()
while line:
print line
line = f.readline()
f.close()
if __name__ == "__main__":
write_file()
read_file()
运行结果:  hello ithomer
my blog: http://blog.ithomer.net
this is the end


  

  文件操作示例:

#/usr/bin/python
#
# ithomer in 2013

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

f = open('test_file.txt','r')           #以读方式打开文件,rb为二进制方式(如图片或可执行文件等)  
print 'read()'                          #读取整个文件  
print f.read()  
print 'readline() f.seek(0)'            #返回文件头,读取一行  
f.seek(0)  
print f.readline()  
print 'readline() f.seek(1)'            #返回文件头,读取一行  
print f.tell()                          #显示当前位置  
f.seek(1)  
print f.tell()                          #显示当前位置  
print f.readline()  
print 'readline() f.seek(10)'          #返回文件头,读取一行  
print f.tell()               
f.seek(10)  
print f.tell()               
print f.readline()  
print f.tell()               
print f.readline()  
print 'readline() f.seek(15)'          #返回文件头,读取一行  
print f.tell()               
f.seek(15)  
print f.tell()               
print f.readline()  
print f.tell()               
print f.readline()  
print 'readlines()'                     #返回文件头,返回所有行的列表  
f.seek(0)  
print f.readlines()  
print
print 'list all lines'                  #返回文件头,显示所有行  
print 'readlines()'                     #返回文件头,返回所有行的列表  
f.seek(0)  
print f.readlines()  
print
print 'list all lines'                  #返回文件头,显示所有行  
f.seek(0)  
textlist = f.readlines()  
for line in textlist:  
print line,  
print   
print 'seek(15) function'               #移位到第15个字符,从16个字符开始显示余下内容  
f.seek(15)  
print 'tell() function'  
print f.tell()                          #显示当前位置  
print f.read()  
f.close()                               #关闭文件句柄  

'''
======== output result  =========
read()
hello world
my blog is ithomer.net
this is end.
readline() f.seek(0)
hello world
readline() f.seek(1)
12
1
ello world
readline() f.seek(10)
12
10
d
12
my blog is ithomer.net
readline() f.seek(15)
35
15
blog is ithomer.net
35
this is end.
readlines()
['hello world\n', 'my blog is ithomer.net\n', 'this is end.\n']
list all lines
readlines()
['hello world\n', 'my blog is ithomer.net\n', 'this is end.\n']
list all lines
hello world
my blog is ithomer.net
this is end.
seek(15) function
tell() function
15
blog is ithomer.net
this is end.
'''


  

python中对文件、文件夹(文件操作函数)的操作需要涉及到os模块和shutil模块


常用操作
得到当前工作目录,即当前Python脚本工作的目录路径:os.getcwd()
返回指定目录下的所有文件和目录名:os.listdir()
函数用来删除一个文件:os.remove()
删除多个目录:os.removedirs(r“c:\python”)
检验给出的路径是否是一个文件:os.path.isfile()
检验给出的路径是否是一个目录:os.path.isdir()
判断是否是绝对路径:os.path.isabs()
检验给出的路径是否真地存:os.path.exists()
返回一个路径的目录名和文件名:os.path.split() eg os.path.split('/home/swaroop/byte/code/poem.txt') 结果:('/home/swaroop/byte/code', 'poem.txt')

分离扩展名:os.path.splitext()
获取路径名:os.path.dirname()
获取文件名:os.path.basename()
运行shell命令:os.system()
读取和设置环境变量:os.getenv() 与os.putenv()
给出当前平台使用的行终止符:os.linesepWindows使用'\r\n',Linux使用'\n'而Mac使用'\r'
指示你正在使用的平台:os.name 对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'
重命名:os.rename(old, new)
创建多级目录:os.makedirs(r“c:\python\test”)
创建单个目录:os.mkdir(“test”)
获取文件属性:os.stat(file)
修改文件权限与时间戳:os.chmod(file)
终止当前进程:os.exit()
获取文件大小:os.path.getsize(filename)

文件操作
os.mknod("test.txt") 创建空文件
fp = open("test.txt",w) 直接打开一个文件,如果文件不存在则创建文件

关于open 模式:
w以写方式打开,
a以追加模式打开 (从 EOF 开始, 必要时创建新文件)
r+以读写模式打开
w+以读写模式打开 (参见 w )
a+以读写模式打开 (参见 a )
rb以二进制读模式打开
wb以二进制写模式打开 (参见 w )
ab以二进制追加模式打开 (参见 a )
rb+以二进制读写模式打开 (参见 r+ )
wb+以二进制读写模式打开 (参见 w+ )
ab+以二进制读写模式打开 (参见 a+ )


fp.read([size])#size为读取的长度,以byte为单位
fp.readline([size]) #读一行,如果定义了size,有可能返回的只是一行的一部分
fp.readlines([size]) #把文件每一行作为一个list的一个成员,并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数,size是表示读取内容的总长,也就是说可能只读到文件的一部分。
fp.write(str) #把str写到文件中,write()并不会在str后加上一个换行符
fp.writelines(seq) #把seq的内容全部写到文件中(多行一次性写入)。这个函数也只是忠实地写入,不会在每行后面加上任何东西。
fp.close() #关闭文件。python会在一个文件不用后自动关闭文件,不过这一功能没有保证,最好还是养成自己关闭的习惯。 如果一个文件在关闭后还对其进行操作会产生ValueError
fp.flush()       #把缓冲区的内容写入硬盘
fp.fileno()  #返回一个长整型的”文件标签“
fp.isatty()  #文件是否是一个终端设备文件(unix系统中的)
fp.tell()     #返回文件操作标记的当前位置,以文件的开头为原点
fp.next()             #返回下一行,并将文件操作标记位移到下一行。把一个file用于for … in file这样的语句时,就是调用next()函数来实现遍历的。
fp.seek(offset[,whence]) #将文件打操作标记移到offset的位置。这个offset一般是相对于文件的开头来计算的,一般为正数。但如果提供了whence参数就不一定了,whence可以为0表示从头开始计算,1表示以当前位置为原点计算。2表示以文件末尾为原点进行计算。需要注意,如果文件以a或a+的模式打开,每次进行写操作时,文件操作标记会自动返回到文件末尾。
fp.truncate([size]) #把文件裁成规定的大小,默认的是裁到当前文件操作标记的位置。如果size比文件的大小还要大,依据系统的不同可能是不改变文件,也可能是用0把文件补到相应的大小,也可能是以一些随机的内容加上去。


目录操作
os.mkdir("file") 创建目录
复制文件:
shutil.copyfile("oldfile","newfile") oldfile和newfile都只能是文件
shutil.copy("oldfile","newfile") oldfile只能是文件夹,newfile可以是文件,也可以是目标目录
复制文件夹:
shutil.copytree("olddir","newdir") olddir和newdir都只能是目录,且newdir必须不存在
重命名文件(目录)
os.rename("oldname","newname") 文件或目录都是使用这条命令
移动文件(目录)
shutil.move("oldpos","newpos")
删除文件
os.remove("file")
删除目录
os.rmdir("dir")只能删除空目录
shutil.rmtree("dir")  空目录、有内容的目录都可以删
转换目录
os.chdir("path") 换路径


操作实例
将文件夹下所有图片名称加上'_fc',python代码:


# -*- coding:utf-8 -*-
import re
import os
import time
#str.split(string)分割字符串
#'连接符'.join(list) 将列表组成字符串
def change_name(path):
global i
if not os.path.isdir(path) and not os.path.isfile(path):
return False
if os.path.isfile(path):
file_path = os.path.split(path) #分割出目录与文件
print(file_path)
lists = file_path[1].split('.') #分割出文件与文件扩展名
file_ext = lists[-1]            #取出后缀名(列表切片操作)
img_ext = ['bmp','jpeg','gif','psd','png','jpg']
if file_ext in img_ext:
path2 = file_path[0]+'/'+lists[0]+'_fc.'+file_ext
os.rename(path, path2)
print("old = %s" % path)
print("new = %s" % path)
i+=1 #注意这里的i是一个陷阱
#或者
#img_ext = 'bmp|jpeg|gif|psd|png|jpg'
#if file_ext in img_ext:
#    print('ok---'+file_ext)
elif os.path.isdir(path):
for x in os.listdir(path):
change_name(os.path.join(path, x)) #os.path.join()在路径处理上很有用
img_dir = '\\home\\homer\\images'
print img_dir
img_dir = img_dir.replace('\\','/')
print img_dir
start = time.time()
i = 0
change_name(img_dir)
c = time.time() - start
print('程序运行耗时:%12.10f'%(c))
print('总共处理了 %s 张图片'%(i))


运行结果:
\home\homer\images
/home/homer/images
('/home/homer/images', '4.png')
old = /home/homer/images/4.png
new = /home/homer/images/4.png
('/home/homer/images', '5.jpg')
old = /home/homer/images/5.jpg
new = /home/homer/images/5.jpg
('/home/homer/images', '3.jpg')
old = /home/homer/images/3.jpg
new = /home/homer/images/3.jpg
('/home/homer/images', '6.png')
old = /home/homer/images/6.png
new = /home/homer/images/6.png
('/home/homer/images', '1.jpg')
old = /home/homer/images/1.jpg
new = /home/homer/images/1.jpg
('/home/homer/images', '2.jpg')
old = /home/homer/images/2.jpg
new = /home/homer/images/2.jpg
程序运行耗时:0.0006089211
总共处理了 6 张图片



  

  参考推荐:
  python对文件进行读写操作

  python文件操作

  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-370083-1-1.html 上篇帖子: python + selenium 自动化框架搭建 下篇帖子: 【Python旧时笔记 二】Python的整数对象:PyIntObject
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表