您的位置:首页 > 编程语言 > Python开发

基础知识(八)python文件操作相关函数

2015-09-25 11:49 986 查看
<span style="font-family: Arial, Helvetica, sans-serif;">import cv2</span>
import csv
import numpy as np
from pandas.io.parsers import read_csv
from matplotlib import pyplot as plt

def writedata(listdata,filepath="newlabel.txt"):
fr=open(filepath,'w')
fr.writelines(listdata)
fr.close()
def readdata(filepath):
filepath
fr=open(filepath,'r')
filesplit=[]
for line in fr.readlines():
s=line.split()
filesplit.append(s);
fr.close()
return filesplit

def IsSubString(SubStrList,Str):
'''''
#判断字符串Str是否包含序列SubStrList中的每一个子字符串
#>>>SubStrList=['F','EMS','txt']
#>>>Str='F06925EMS91.txt'
#>>>IsSubString(SubStrList,Str)#return True (or False)
'''
flag=True
for substr in SubStrList:
if not(substr in Str):
flag=False

return flag
#~ #----------------------------------------------------------------------
def GetFileList(FindPath,FlagStr=[]):
'''''
#获取目录中指定的文件名
#>>>FlagStr=['F','EMS','txt'] #要求文件名称中包含这些字符
#>>>FileList=GetFileList(FindPath,FlagStr) #
'''
import os
FileList=[]
FileNames=os.listdir(FindPath)
if (len(FileNames)>0):
for fn in FileNames:
if (len(FlagStr)>0):
#返回指定类型的文件名
if (IsSubString(FlagStr,fn)):
fullfilename=os.path.join(FindPath,fn)
FileList.append(fullfilename)
else:
#默认直接返回所有文件名
fullfilename=os.path.join(FindPath,fn)
FileList.append(fullfilename)

#对文件名排序
if (len(FileList)>0):
FileList.sort()

return FileList

cv2.namedWindow('facerect')
label=readdata('fold_0_data.txt')

labelcor=[]
for i in range(100):
if i==0:

continue
FileList=GetFileList('imagedata\\'+label[i][0],['jpg'])
for imgp in FileList:
if label[i][1] in imgp:
newl=[]
newl.append(imgp)
newl.append(label[i][5])
newl.append(label[i][4])
labelcor.append(newl)
break
#去除一张图片中有多个人,多个标签的图片
twocout=[]
for l in labelcor:
twocout.append(l[0])

from collections import Counter
counter=Counter(twocout)

indexnew=[]
for key in counter:
if counter[key]==1:
indexnew.append(twocout.index(key))

resultfile=[]
for i in indexnew:
l=labelcor[i]
s = '\t'.join(l) + '\n'
resultfile.append(s)

writedata(resultfile)
'''img = plt.imread(l[0])
plt.imshow(img)
plt.title(l[1])
while True:
if cv2.waitKey(0)==13:
break'''

cv2.destroyAllWindows()

二、重命名

os.rename(oldname,newname)

三、人脸裁剪

filesplit=readdata('yellow.txt')
for s in filesplit:
if len(s)!=5:
continue
img = cv2.imread(s[0])
height, weight =np.shape(img)[:2]
x1, x2, y1, y2 =[int(x) for x in s[1:]]
x=int(x1)
y=int(y1)
w=int(x2-x1)
h=int(y2-y1)
img0=np.zeros((h+0.2*h,w+0.2*w,3))
m,n,c=img0.shape
miny=max(0,y-0.3*h)
minx=max(0,(x-0.3*w))
maxy=min(height,(y+1.3*h))
maxx=min(weight,(x+1.3*w))
roi=img[miny:maxy,minx:maxx]
rectshape=roi.shape
maxlenght=max(rectshape[0],rectshape[1])
img0=np.zeros((maxlenght,maxlenght,3))
img0[(maxlenght*.5-rectshape[0]*.5):(maxlenght*.5+rectshape[0]*.5),(maxlenght*.5-rectshape[1]*.5):(maxlenght*.5+rectshape[1]*.5)]=roi
cv2.imwrite('crop'+s[0],img0)

四\文件操作/article/8336257.html

'''''
Python常见文件操作示例

os.path 模块中的路径名访问函数
分隔
basename() 去掉目录路径, 返回文件名
dirname() 去掉文件名, 返回目录路径
join() 将分离的各部分组合成一个路径名
split() 返回 (dirname(), basename()) 元组
splitdrive() 返回 (drivename, pathname) 元组
splitext() 返回 (filename, extension) 元组

信息
getatime() 返回最近访问时间
getctime() 返回文件创建时间
getmtime() 返回最近文件修改时间
getsize() 返回文件大小(以字节为单位)

查询
exists() 指定路径(文件或目录)是否存在
isabs() 指定路径是否为绝对路径
isdir() 指定路径是否存在且为一个目录
isfile() 指定路径是否存在且为一个文件
islink() 指定路径是否存在且为一个符号链接
ismount() 指定路径是否存在且为一个挂载点
samefile() 两个路径名是否指向同个文件

os.path.isdir(name):判断name是不是一个目录,name不是目录就返回false
os.path.isfile(name):判断name是不是一个文件,不存在name也返回false
os.path.exists(name):判断是否存在文件或目录name
os.path.getsize(name):获得文件大小,如果name是目录返回0L
os.path.abspath(name):获得绝对路径
os.path.normpath(path):规范path字符串形式
os.path.split(name):分割文件名与目录(事实上,如果你完全使用目录,它也会将最后一个目录作为文件名而分离,同时它不会判断文件或目录是否存在)
os.path.splitext():分离文件名与扩展名
os.path.join(path,name):连接目录与文件名或目录
os.path.basename(path):返回文件名
os.path.dirname(path):返回文件路径

os模块中的文件操作:
os 模块属性
linesep 用于在文件中分隔行的字符串
sep 用来分隔文件路径名的字符串
pathsep 用于分隔文件路径的字符串
curdir 当前工作目录的字符串名称
pardir (当前工作目录的)父目录字符串名称

1.重命名:os.rename(old, new)

2.删除:os.remove(file)

3.列出目录下的文件:os.listdir(path)

4.获取当前工作目录:os.getcwd()

5.改变工作目录:os.chdir(newdir)

6.创建多级目录:os.makedirs(r"c:\python\test")

7.创建单个目录:os.mkdir("test")

8.删除多个目录:os.removedirs(r"c:\python") #删除所给路径最后一个目录下所有空目录。

9.删除单个目录:os.rmdir("test")

10.获取文件属性:os.stat(file)

11.修改文件权限与时间戳:os.chmod(file)

12.执行操作系统命令:os.system("dir")

13.启动新进程:os.exec(), os.execvp()

14.在后台执行程序:osspawnv()

15.终止当前进程:os.exit(), os._exit()

16.分离文件名:os.path.split(r"c:\python\hello.py") --> ("c:\\python", "hello.py")

17.分离扩展名:os.path.splitext(r"c:\python\hello.py") --> ("c:\\python\\hello", ".py")

18.获取路径名:os.path.dirname(r"c:\python\hello.py") --> "c:\\python"

19.获取文件名:os.path.basename(r"r:\python\hello.py") --> "hello.py"

20.判断文件是否存在:os.path.exists(r"c:\python\hello.py") --> True

21.判断是否是绝对路径:os.path.isabs(r".\python\") --> False

22.判断是否是目录:os.path.isdir(r"c:\python") --> True

23.判断是否是文件:os.path.isfile(r"c:\python\hello.py") --> True

24.判断是否是链接文件:os.path.islink(r"c:\python\hello.py") --> False

25.获取文件大小:os.path.getsize(filename)

26.*******:os.ismount("c:\\") --> True

27.搜索目录下的所有文件:os.path.walk()

shutil模块对文件的操作:
1.复制单个文件:shultil.copy(oldfile, newfle)

2.复制整个目录树:shultil.copytree(r".\setup", r".\backup")

3.删除整个目录树:shultil.rmtree(r".\backup")

临时文件的操作:
1.创建一个唯一的临时文件:tempfile.mktemp() --> filename

2.打开临时文件:tempfile.TemporaryFile()

内存文件(StringIO和cStringIO)操作
[4.StringIO] #cStringIO是StringIO模块的快速实现模块

1.创建内存文件并写入初始数据:f = StringIO.StringIO("Hello world!")

2.读入内存文件数据:print f.read() #或print f.getvalue() --> Hello world!

3.想内存文件写入数据:f.write("Good day!")

4.关闭内存文件:f.close()


复制代码
os.sep    可以取代操作系统特定的路径分隔符。windows下为 '\\'
os.name    字符串指示你正在使用的平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是 'posix'
os.getcwd()    函数得到当前工作目录,即当前Python脚本工作的目录路径
os.getenv()    获取一个环境变量,如果没有返回none
os.putenv(key, value)    设置一个环境变量值
os.listdir(path)    返回指定目录下的所有文件和目录名
os.remove(path)    函数用来删除一个文件
os.system(command)    函数用来运行shell命令
os.linesep    字符串给出当前平台使用的行终止符。例如,Windows使用 '\r\n',Linux使用 '\n' 而Mac使用 '\r'
os.path.split(path)        函数返回一个路径的目录名和文件名
os.path.isfile()    和os.path.isdir()函数分别检验给出的路径是一个文件还是目录
os.path.exists()    函数用来检验给出的路径是否真地存在
os.curdir        返回当前目录 ('.')
os.mkdir(path)    创建一个目录
os.makedirs(path)    递归的创建目录
os.chdir(dirname)    改变工作目录到dirname
os.path.getsize(name)    获得文件大小,如果name是目录返回0L
os.path.abspath(name)    获得绝对路径
os.path.normpath(path)    规范path字符串形式
os.path.splitext()        分离文件名与扩展名
os.path.join(path,name)    连接目录与文件名或目录
os.path.basename(path)    返回文件名
os.path.dirname(path)    返回文件路径
os.walk(top,topdown=True,onerror=None)        遍历迭代目录
os.rename(src, dst)        重命名file或者directory src到dst 如果dst是一个存在的directory, 将抛出OSError. 在Unix, 如果dst在存且是一个file, 如果用户有权限的话,它将被安静的替换. 操作将会失败在某些Unix 中如果src和dst在不同的文件系统中. 如果成功, 这命名操作将会是一个原子操作 (这是POSIX 需要). 在 Windows上, 如果dst已经存在, 将抛出OSError,即使它是一个文件. 在unix,Windows中有效。
os.renames(old, new)    递归重命名文件夹或者文件。像rename()

# shutil 模块

shutil.copyfile( src, dst)    从源src复制到dst中去。当然前提是目标地址是具备可写权限。抛出的异常信息为IOException. 如果当前的dst已存在的话就会被覆盖掉
shutil.move( src, dst)        移动文件或重命名
shutil.copymode( src, dst)    只是会复制其权限其他的东西是不会被复制的
shutil.copystat( src, dst)    复制权限、最后访问时间、最后修改时间
shutil.copy( src, dst)        复制一个文件到一个文件或一个目录
shutil.copy2( src, dst)        在copy上的基础上再复制文件最后访问时间与修改时间也复制过来了,类似于cp –p的东西
shutil.copy2( src, dst)        如果两个位置的文件系统是一样的话相当于是rename操作,只是改名;如果是不在相同的文件系统的话就是做move操作
shutil.copytree( olddir, newdir, True/Flase)
把olddir拷贝一份newdir,如果第3个参数是True,则复制目录时将保持文件夹下的符号连接,如果第3个参数是False,则将在复制的目录下生成物理副本来替代符号连接
shutil.rmtree( src )    递归删除一个目录以及目录内的所有内容
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: