<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
	<channel>
		<atom:link href="http://itecfun.com/extern.php?action=feed&amp;tid=3184&amp;type=rss" rel="self" type="application/rss+xml" />
		<title><![CDATA[个人知识管理站 / python文件操作]]></title>
		<link>http://www.itecfun.com/viewtopic.php?id=3184</link>
		<description><![CDATA[python文件操作 最近发表的帖子。]]></description>
		<lastBuildDate>Fri, 03 Jul 2015 03:45:33 +0000</lastBuildDate>
		<generator>FluxBB</generator>
		<item>
			<title><![CDATA[python文件操作]]></title>
			<link>http://www.itecfun.com/viewtopic.php?pid=3354#p3354</link>
			<description><![CDATA[<p>python中对文件、文件夹（文件操作函数）的操作需要涉及到os模块和shutil模块。</p><p>得到当前工作目录，即当前Python脚本工作的目录路径: os.getcwd()</p><p>返回指定目录下的所有文件和目录名:os.listdir()</p><p>函数用来删除一个文件:os.remove()</p><p>删除多个目录：os.removedirs（r“c：python”）</p><p>检验给出的路径是否是一个文件：os.path.isfile()</p><p>检验给出的路径是否是一个目录：os.path.isdir()</p><p>判断是否是绝对路径：os.path.isabs()</p><p>检验给出的路径是否真地存:os.path.exists()</p><p>返回一个路径的目录名和文件名:os.path.split()&#160; &#160; &#160;eg os.path.split(&#039;/home/swaroop/byte/code/poem.txt&#039;) 结果：(&#039;/home/swaroop/byte/code&#039;, &#039;poem.txt&#039;) </p><p>分离扩展名：os.path.splitext()</p><p>获取路径名：os.path.dirname()</p><p>获取文件名：os.path.basename()</p><p>运行shell命令: os.system()</p><p>读取和设置环境变量:os.getenv() 与os.putenv()</p><p>给出当前平台使用的行终止符:os.linesep&#160; &#160; Windows使用&#039;\r\n&#039;，Linux使用&#039;\n&#039;而Mac使用&#039;\r&#039;</p><p>指示你正在使用的平台：os.name&#160; &#160; &#160; &#160;对于Windows，它是&#039;nt&#039;，而对于Linux/Unix用户，它是&#039;posix&#039;</p><p>重命名：os.rename（old， new）</p><p>创建多级目录：os.makedirs（r“c：python\test”）</p><p>创建单个目录：os.mkdir（“test”）</p><p>获取文件属性：os.stat（file）</p><p>修改文件权限与时间戳：os.chmod（file）</p><p>终止当前进程：os.exit（）</p><p>获取文件大小：os.path.getsize（filename）</p><br /><p>文件操作：<br />os.mknod(&quot;test.txt&quot;)&#160; &#160; &#160; &#160; 创建空文件<br />fp = open(&quot;test.txt&quot;,w)&#160; &#160; &#160;直接打开一个文件，如果文件不存在则创建文件</p><p>关于open 模式：</p><p>w&#160; &#160; &#160;以写方式打开，<br />a&#160; &#160; &#160;以追加模式打开 (从 EOF 开始, 必要时创建新文件)<br />r+&#160; &#160; &#160;以读写模式打开<br />w+&#160; &#160; &#160;以读写模式打开 (参见 w )<br />a+&#160; &#160; &#160;以读写模式打开 (参见 a )<br />rb&#160; &#160; &#160;以二进制读模式打开<br />wb&#160; &#160; &#160;以二进制写模式打开 (参见 w )<br />ab&#160; &#160; &#160;以二进制追加模式打开 (参见 a )<br />rb+&#160; &#160; 以二进制读写模式打开 (参见 r+ )<br />wb+&#160; &#160; 以二进制读写模式打开 (参见 w+ )<br />ab+&#160; &#160; 以二进制读写模式打开 (参见 a+ )</p><p> </p><p>fp.read([size])&#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160;#size为读取的长度，以byte为单位</p><p>fp.readline([size])&#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160;#读一行，如果定义了size，有可能返回的只是一行的一部分</p><p>fp.readlines([size])&#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; #把文件每一行作为一个list的一个成员，并返回这个list。其实它的内部是通过循环调用readline()来实现的。如果提供size参数，size是表示读取内容的总长，也就是说可能只读到文件的一部分。</p><p>fp.write(str)&#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; #把str写到文件中，write()并不会在str后加上一个换行符</p><p>fp.writelines(seq)&#160; &#160; &#160; &#160; &#160; &#160; #把seq的内容全部写到文件中(多行一次性写入)。这个函数也只是忠实地写入，不会在每行后面加上任何东西。</p><p>fp.close()&#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; #关闭文件。python会在一个文件不用后自动关闭文件，不过这一功能没有保证，最好还是养成自己关闭的习惯。&#160; 如果一个文件在关闭后还对其进行操作会产生ValueError</p><p>fp.flush()&#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; #把缓冲区的内容写入硬盘</p><p>fp.fileno()&#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; #返回一个长整型的”文件标签“</p><p>fp.isatty()&#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; #文件是否是一个终端设备文件（unix系统中的）</p><p>fp.tell()&#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160;#返回文件操作标记的当前位置，以文件的开头为原点</p><p>fp.next()&#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160;#返回下一行，并将文件操作标记位移到下一行。把一个file用于for … in file这样的语句时，就是调用next()函数来实现遍历的。</p><p>fp.seek(offset[,whence])&#160; &#160; &#160; &#160; &#160; &#160; &#160; #将文件打操作标记移到offset的位置。这个offset一般是相对于文件的开头来计算的，一般为正数。但如果提供了whence参数就不一定了，whence可以为0表示从头开始计算，1表示以当前位置为原点计算。2表示以文件末尾为原点进行计算。需要注意，如果文件以a或a+的模式打开，每次进行写操作时，文件操作标记会自动返回到文件末尾。</p><p>fp.truncate([size])&#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160;#把文件裁成规定的大小，默认的是裁到当前文件操作标记的位置。如果size比文件的大小还要大，依据系统的不同可能是不改变文件，也可能是用0把文件补到相应的大小，也可能是以一些随机的内容加上去。</p><p> </p><p>目录操作：<br />os.mkdir(&quot;file&quot;)&#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160; &#160;创建目录<br />复制文件：<br />shutil.copyfile(&quot;oldfile&quot;,&quot;newfile&quot;)&#160; &#160; &#160; &#160;oldfile和newfile都只能是文件<br />shutil.copy(&quot;oldfile&quot;,&quot;newfile&quot;)&#160; &#160; &#160; &#160; &#160; &#160; oldfile只能是文件夹，newfile可以是文件，也可以是目标目录<br />复制文件夹：<br />shutil.copytree(&quot;olddir&quot;,&quot;newdir&quot;)&#160; &#160; &#160; &#160; olddir和newdir都只能是目录，且newdir必须不存在<br />重命名文件（目录）<br />os.rename(&quot;oldname&quot;,&quot;newname&quot;)&#160; &#160; &#160; &#160;文件或目录都是使用这条命令<br />移动文件（目录）<br />shutil.move(&quot;oldpos&quot;,&quot;newpos&quot;)&#160; &#160;<br />删除文件<br />os.remove(&quot;file&quot;)<br />删除目录<br />os.rmdir(&quot;dir&quot;)只能删除空目录<br />shutil.rmtree(&quot;dir&quot;)&#160; &#160; 空目录、有内容的目录都可以删<br />转换目录<br />os.chdir(&quot;path&quot;)&#160; &#160;换路径</p><p> </p><p>相关例子 </p><p> 1 将文件夹下所有图片名称加上&#039;_fc&#039;</p><p>python代码:</p><p># -*- coding:utf-8 -*-<br />import re<br />import os<br />import time<br />#str.split(string)分割字符串<br />#&#039;连接符&#039;.join(list) 将列表组成字符串<br />def change_name(path):<br />&#160; &#160; global i<br />&#160; &#160; if not os.path.isdir(path) and not os.path.isfile(path):<br />&#160; &#160; &#160; &#160; return False<br />&#160; &#160; if os.path.isfile(path):<br />&#160; &#160; &#160; &#160; file_path = os.path.split(path) #分割出目录与文件<br />&#160; &#160; &#160; &#160; lists = file_path[1].split(&#039;.&#039;) #分割出文件与文件扩展名<br />&#160; &#160; &#160; &#160; file_ext = lists[-1] #取出后缀名(列表切片操作)<br />&#160; &#160; &#160; &#160; img_ext = [&#039;bmp&#039;,&#039;jpeg&#039;,&#039;gif&#039;,&#039;psd&#039;,&#039;png&#039;,&#039;jpg&#039;]<br />&#160; &#160; &#160; &#160; if file_ext in img_ext:<br />&#160; &#160; &#160; &#160; &#160; &#160; os.rename(path,file_path[0]+&#039;/&#039;+lists[0]+&#039;_fc.&#039;+file_ext)<br />&#160; &#160; &#160; &#160; &#160; &#160; i+=1 #注意这里的i是一个陷阱<br />&#160; &#160; &#160; &#160; #或者<br />&#160; &#160; &#160; &#160; #img_ext = &#039;bmp|jpeg|gif|psd|png|jpg&#039;<br />&#160; &#160; &#160; &#160; #if file_ext in img_ext:<br />&#160; &#160; &#160; &#160; #&#160; &#160; print(&#039;ok---&#039;+file_ext)<br />&#160; &#160; elif os.path.isdir(path):<br />&#160; &#160; &#160; &#160; for x in os.listdir(path):<br />&#160; &#160; &#160; &#160; &#160; &#160; change_name(os.path.join(path,x)) #os.path.join()在路径处理上很有用</p><br /><p>img_dir = &#039;D:\\xx\\xx\\images&#039;<br />img_dir = img_dir.replace(&#039;\\&#039;,&#039;/&#039;)<br />start = time.time()<br />i = 0<br />change_name(img_dir)<br />c = time.time() - start<br />print(&#039;程序运行耗时:%0.2f&#039;%(c))<br />print(&#039;总共处理了 %s 张图片&#039;%(i))<br />输出结果：</p><p>程序运行耗时:0.11<br />总共处理了 109 张图片</p><p>本文出处：<br /><a href="http://www.cnblogs.com/rollenholt/archive/2012/04/23/2466179.html" rel="nofollow">http://www.cnblogs.com/rollenholt/archi … 66179.html</a></p>]]></description>
			<author><![CDATA[dummy@example.com (xuyg)]]></author>
			<pubDate>Fri, 03 Jul 2015 03:45:33 +0000</pubDate>
			<guid>http://www.itecfun.com/viewtopic.php?pid=3354#p3354</guid>
		</item>
	</channel>
</rss>
