上代码:

import os

import os.path

rootdir = "d:/code/su/data" # 指明被遍历的文件夹

for parent,dirnames,filenames in os.walk(rootdir): #三个参数:分别返回1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字

for dirname in dirnames: #输出文件夹信息

print "parent is:" + parent

print "dirname is" + dirname

for filename in filenames: #输出文件信息

print "parent is:" + parent

print "filename is:" + filename

print "the full name of the file is:" + os.path.join(parent,filename) #输出文件路径信息

按照博主的理解,每个元组代表的含义是线程处于某一个状态的影像。目录树的遍历过程就是由这一个一个的状态构成的。在每个状态下, 线程获得一个目录节点,同时获得这个目录节点下的所有目录节点和文件节点。

如果只需要获得单个目录节点的子节点:

os.listdir(rootdir)

基于字符read & write

最基本的文件操作当然就是在文件中读写数据。这也是很容易掌握的。现在打开一个文件以进行写操作:

1. fileHandle = open ( 'test.txt', 'w' )

fileHandle = open ( 'test.txt', 'w' )

'w'是指文件将被写入数据,语句的其它部分很好理解。下一步就是将数据写入文件:

1. fileHandle.write ( 'This is a test.\nReally, it is.' )

fileHandle.write ( 'This is a test.\nReally, it is.' )

这个语句将"This is a test."写入文件的第一行,"Really, it is."写入文件的第二行。最后,我们需要做清理工作,并且关闭文件:

1. fileHandle.close()

fileHandle.close()

正如你所见,在Python的面向对象机制下,这确实非常简单。需要注意的是,当你再次使用"w"方式在文件中写数据,所有原来的内容都会被删除。如果想保留原来的内容,可以使用"a"方式在文件中结尾附加数据:

1. fileHandle = open ( 'test.txt', 'a' ) 
2. fileHandle.write ( '\n\nBottom line.' ) 
3. fileHandle.close()

fileHandle = open ( 'test.txt', 'a' ) 
fileHandle.write ( '\n\nBottom line.' ) 
fileHandle.close()

然后,我们读取test.txt,并将内容显示出来:

1. fileHandle = open ( 'test.txt' ) 
2. print fileHandle.read() 
3. fileHandle.close()

fileHandle = open ( 'test.txt' ) 
print fileHandle.read() 
fileHandle.close()

以上语句将读取整个文件并显示其中的数据。

基于行的读写 line

1. fileHandle = open ( 'test.txt' )  
2. print fileHandle.readline() # "This is a test."  
3. fileHandle.close()

fileHandle = open ( 'test.txt' ) 
print fileHandle.readline() # "This is a test." 
fileHandle.close()

同时,也可以将文件内容保存到一个list中:

1. fileHandle = open ( 'test.txt' )  
2. fileList = fileHandle.readlines()  
3. for fileLine in fileList:  
4.     print '>>', fileLine  
5. fileHandle.close()

fileHandle = open ( 'test.txt' ) 
fileList = fileHandle.readlines() 
for fileLine in fileList: 
print '>>', fileLine 
fileHandle.close()

或者在文件中一次读取几个字节的内容:

1. fileHandle = open ( 'test.txt' ) 
2. print fileHandle.read ( 1 ) # "T" 
3. fileHandle.seek ( 4 ) 
4. print FileHandle.read ( 1 ) # " "(原文有错)

fileHandle = open ( 'test.txt' ) 
print fileHandle.read ( 1 ) # "T" 
fileHandle.seek ( 4 ) 
print FileHandle.read ( 1 ) # " "(原文有错)

随机访问文件中的位置 seek

Python在读取一个文件时,会记住其在文件中的位置,如下所示:

1. fileHandle = open ( 'test.txt' ) 
2. garbage = fileHandle.readline() 
3. fileHandle.readline() # "Really, it is."fileHandle.close()

fileHandle = open ( 'test.txt' ) 
garbage = fileHandle.readline() 
fileHandle.readline() # "Really, it is."fileHandle.close()

可以看到,只有第二行显示出来。然而,我们可以让Python从头开始读来解决这个问题:

1. fileHandle = open ( 'test.txt' ) 
2. garbage = fileHandle.readline() 
3. fileHandle.seek ( 0 ) 
4. print fileHandle.readline() # "This is a test." 
5. fileHandle.close()

fileHandle = open ( 'test.txt' ) 
garbage = fileHandle.readline() 
fileHandle.seek ( 0 ) 
print fileHandle.readline() # "This is a test." 
fileHandle.close()

在上面这个例子中,我们让Python从文件第一个字节开始读取数据。所以,第一行文字显示了出来。当然,我们也可以获取Python在文件中的位置:

1. fileHandle = open ( 'test.txt' ) 
2. print fileHandle.readline() # "This is a test." 
3. print fileHandle.tell() # "17" 
4. print fileHandle.readline() # "Really, it is."

fileHandle = open ( 'test.txt' ) 
print fileHandle.readline() # "This is a test." 
print fileHandle.tell() # "17" 
print fileHandle.readline() # "Really, it is."

二进制方式读写

在Windows和Macintosh环境下,有时可能需要以二进制方式读写文件,比如图片和可执行文件。此时,只要在打开文件的方式参数中增加一个"b"即可:

1. fileHandle = open ( 'testBinary.txt', 'wb' ) 
2. fileHandle.write ( 'There is no spoon.' ) 
3. fileHandle.close()

fileHandle = open ( 'testBinary.txt', 'wb' ) 
fileHandle.write ( 'There is no spoon.' ) 
fileHandle.close()

1. fileHandle = open ( 'testBinary.txt', 'rb' ) 
2. print fileHandle.read() 
3. fileHandle.close()

fileHandle = open ( 'testBinary.txt', 'rb' ) 
print fileHandle.read() 
fileHandle.close()

python本身并没有对二进制进行支持,不过提供了一个模块来弥补,就是struct模块。

python没有二进制类型,但可以存储二进制类型的数据,就是用string字符串类型来存储二进制数据,这也没关系,因为string是以1个字节为单位的。

import struct

a=12.34

#将a变为二进制

bytes=struct.pack('i',a)

此时bytes就是一个string字符串,字符串按字节同a的二进制存储内容相同。

再进行反操作

现有二进制数据bytes,(其实就是字符串),将它反过来转换成python的数据类型:

a,=struct.unpack('i',bytes)

注意,unpack返回的是tuple

所以如果只有一个变量的话:

bytes=struct.pack('i',a)

那么,解码的时候需要这样

a,=struct.unpack('i',bytes) 或者 (a,)=struct.unpack('i',bytes)

如果直接用a=struct.unpack('i',bytes),那么 a=(12.34,) ,是一个tuple而不是原来的浮点数了。

如果是由多个数据构成的,可以这样:

a='hello'

b='world!'

c=2

d=45.123

bytes=struct.pack('5s6sif',a,b,c,d)

此时的bytes就是二进制形式的数据了,可以直接写入文件比如 binfile.write(bytes)

然后,当我们需要时可以再读出来,bytes=binfile.read()

再通过struct.unpack()解码成python变量
a,b,c,d=struct.unpack('5s6sif',bytes)

'5s6sif'这个叫做fmt,就是格式化字符串,由数字加字符构成,5s表示占5个字符的字符串,2i,表示2个整数等等,下面是可用的字符及类型,ctype表示可以与python中的类型一一对应。

===============================================================================================

各种系统操作

注意:虽然python中提供了各种拼接目录的函数,但是经本人实验,函数并不能保证字符编码不出问题,很大可能导致程序错误。所以最好还是自己拼接。

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.islink ( filename )

检验给出的路径是否真地存: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.linesep Windows使用'\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") 换路径

ps: 文件操作时,常常配合正则表达式:

img_dir = img_dir.replace('\\','/')

===============================================================================================

存储对象

使用前一节中介绍的模块,可以实现在文件中对字符串的读写。 
然而,有的时候,你可能需要传递其它类型的数据,如list、tuple、dictionary和其它对象。在Python中,你可以使用Pickling来完成。你可以使用Python标准库中的"pickle"模块完成数据编组。 
下面,我们来编组一个包含字符串和数字的list:

1. import pickle 
2. 
3. fileHandle = open ( 'pickleFile.txt', 'w' ) 
4. testList = [ 'This', 2, 'is', 1, 'a', 0, 'test.' ] 
5. pickle.dump ( testList, fileHandle ) 
6. fileHandle.close()

import pickle

fileHandle = open ( 'pickleFile.txt', 'w' ) 
testList = [ 'This', 2, 'is', 1, 'a', 0, 'test.' ] 
pickle.dump ( testList, fileHandle ) 
fileHandle.close()

拆分编组同样不难:

1. import pickle 
2. 
3. fileHandle = open ( 'pickleFile.txt' ) 
4. testList = pickle.load ( fileHandle ) 
5. fileHandle.close()

import pickle

fileHandle = open ( 'pickleFile.txt' ) 
testList = pickle.load ( fileHandle ) 
fileHandle.close()

现在试试存储更加复杂的数据:

1. import pickle 
2. 
3. fileHandle = open ( 'pickleFile.txt', 'w' ) 
4. testList = [ 123, { 'Calories' : 190 }, 'Mr. Anderson', [ 1, 2, 7 ] ] 
5. pickle.dump ( testList, fileHandle ) 
6. fileHandle.close()

import pickle

fileHandle = open ( 'pickleFile.txt', 'w' ) 
testList = [ 123, { 'Calories' : 190 }, 'Mr. Anderson', [ 1, 2, 7 ] ] 
pickle.dump ( testList, fileHandle ) 
fileHandle.close()

1. import pickle 
2. 
3. fileHandle = open ( 'pickleFile.txt' ) 
4. testList = pickle.load ( fileHandle ) 
5. fileHandle.close()

import pickle

fileHandle = open ( 'pickleFile.txt' ) 
testList = pickle.load ( fileHandle ) 
fileHandle.close()

如上所述,使用Python的"pickle"模块编组确实很简单。众多对象可以通过它来存储到文件中。如果可以的话,"cPickle"同样胜任这个工作。它和"pickle"模块一样,但是速度更快:

1. import cPickle 
2. 
3. fileHandle = open ( 'pickleFile.txt', 'w' ) 
4. cPickle.dump ( 1776, fileHandle ) 
5. fileHandle.close()

import cPickle

fileHandle = open ( 'pickleFile.txt', 'w' ) 
cPickle.dump ( 1776, fileHandle ) 
fileHandle.close()

字符串匹配

对于简单的数据,使用流文本文件而不是数据库更简单明了,也就少不了文件操作和字符串匹配的需求。

re模块的search和match方法是匹配到就返回,而不是去匹配所有,而findall()则匹配所有返回数组。
 >>> m=re.findall("^a\w+","abcdfa\na1b2c3",re.MULTILINE)
 >>> m
 ['abcdfa', 'a1b2c3']

Python 中文件操作的更多相关文章

  1. python中文件操作的六种模式及对文件某一行进行修改的方法

    一.python中文件操作的六种模式分为:r,w,a,r+,w+,a+ r叫做只读模式,只可以读取,不可以写入 w叫做写入模式,只可以写入,不可以读取 a叫做追加写入模式,只可以在末尾追加内容,不可以 ...

  2. python中文件操作的其他方法

    前面介绍过Python中文件操作的一般方法,包括打开,写入,关闭.本文中介绍下python中关于文件操作的其他比较常用的一些方法. 首先创建一个文件poems: p=open('poems','r', ...

  3. python中文件操作的基本方法

    在python中对一个文件进行操作,分为三大步:打开,操作,关闭 首先创建一个文件hello,里面内容为hello world 一.打开一个文件 1.#open(‘文件名或文件路径’,‘操作模式’,文 ...

  4. Python中文件操作2——shutil模块

    1 文件操作 文件有很多的操作,之前的文件操作中介绍了内建函数对文件的打开.读取以及写入,这三种操作是对文件基本的使用.文件还有复制.删除.移动.改变文件的属主属组等操作.下面主要看os模块和shut ...

  5. python中文件操作

      打印进度条

  6. python 中文件输入输出及os模块对文件系统的操作

    整理了一下python 中文件的输入输出及主要介绍一些os模块中对文件系统的操作. 文件输入输出 1.内建函数open(file_name,文件打开模式,通用换行符支持),打开文件返回文件对象. 2. ...

  7. Python :open文件操作,配合read()使用!

    python:open/文件操作 open/文件操作f=open('/tmp/hello','w') #open(路径+文件名,读写模式) 如何打开文件 handle=open(file_name,a ...

  8. Python 常见文件操作的函数示例(转)

    转自:http://www.cnblogs.com/txw1958/archive/2012/03/08/2385540.html # -*-coding:utf8 -*- ''''' Python常 ...

  9. 孤荷凌寒自学python第三十五天python的文件操作之针对文件操作的os模块的相关内容

     孤荷凌寒自学python第三十五天python的文件操作之针对文件操作的os模块的相关内容 (完整学习过程屏幕记录视频地址在文末,手写笔记在文末) 一.打开文件后,要务必记得关闭,所以一般的写法应当 ...

随机推荐

  1. 前端逼死强迫症系列之javascript续集

    一.javascript函数 1.普通函数 function func(){ } 2.匿名函数 setInterval(function(){ console.log(123); },5000) 3. ...

  2. CF2B The least round way(贪心+动规)

    题目 CF2B The least round way 做法 后面\(0\)的个数,\(2\)和\(5\)是\(10\)分解质因数 则把方格中的每个数分解成\(2\)和\(5\),对\(2\)和\(5 ...

  3. [线性代数] 矩阵代数進階:矩阵分解 Matrix factorization

    Matrix factorization 导语:承载上集的矩阵代数入门,今天来聊聊进阶版,矩阵分解.其他集数可在[线性代数]标籤文章找到.有空再弄目录什麽的. Matrix factorization ...

  4. [转载]workbench分网---mapped face meshing面映射网格划分

    原文地址:face meshing面映射网格划分">workbench分网---mapped face meshing面映射网格划分作者:一丝尘埃 face meshing面映射网格划 ...

  5. 使用python3安装frida-tools出错

    执行安装命令 pip3.6 install frida-tools 得到错误信息 error: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] c ...

  6. linux下如何让控制台程序后台运行

    方法1:./test & 方法2:(./test &) 方法3:nohup 和bg 方法4:screen -mS test /root/test   退出程序需要手动进入screen创 ...

  7. Link static data in sql source control

    You can link data that doesn't change very often to SQL Source Control. This lets you commit data ch ...

  8. css 文本省略号设置

    本文推荐2种方法. 1. css tip:只兼容chrome内核的浏览器.ff不支持. .box { overflow: hidden; /* 溢出时不显示溢出的内容 */ text-overflow ...

  9. Vrms、Vpk、W、dBm、dBW、dBuV、dBm/Hz

    负载阻抗Z 在做这些单位转换前第一个需要提到的就是负载阻抗(Z, Ohm),我们在测试测量中说某个量为上面的某一个单位时候,都包含了一个前提条件,那就是负载阻抗,离开了负载阻抗你说的这些总带有一丝耍流 ...

  10. Leetcode: Find First and Last Position of Element in Sorted Array

    Given a sorted array of integers, find the starting and ending position of a given target value. You ...