记录常用的文件写入、读取、文件、目录的操作。
1、文件写入
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 |
import time
import random
#打开模式列表:
#w 以写方式打开,
#a 以追加模式打开 (从 EOF 开始, 必要时创建新文件)
#r+ 以读写模式打开
#w+ 以读写模式打开 (参见 w )
#a+ 以读写模式打开 (参见 a )
#rb 以二进制读模式打开
#wb 以二进制写模式打开 (参见 w )
#ab 以二进制追加模式打开 (参见 a )
#rb+ 以二进制读写模式打开 (参见 r+ )
#wb+ 以二进制读写模式打开 (参见 w+ )
#ab+ 以二进制读写模式打开 (参见 a+ )
f = open ( 'tpm.txt' , 'a+' )
for i in range ( 10 ) :
f.write(time.strftime( '%Y-%m-%d %H:%M:%S' ))
f.write( ' ' + str (random.randint( 0 , i)) + '\n' )
f.close()
|
2、文件读取
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15 |
f = open ( 'tpm.txt' )
# read方式读取
s = f.read()
print (s, '\n\n\n' )
print (f.tell())
#上面读取完后指针移动到最后,通过seek将文件指针移动到文件头
f.seek( 0 )
#使用readline每次读取一行
while ( True ):
line = f.readline()
print (line)
if ( len (line) = = 0 ):
break
f.close()
|
3、文件目录操作(OS包)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25 |
#os模块,处理文件和目录的一系列函数
import os
#打印当前目录下的所有文件 非递归
print (os.listdir(os.getcwd()))
#切换目录为当前目录
os.chdir( '.' )
#判断目标是否存在,不存在则创建
if (os.path.exists( './osdirs' ) = = False ):
os.mkdir( "./osdirs" )
#重命名文件或目录名
if (os.path.exists( "./os" ) = = False ) :
os.rename( "./osdirs" , "./os" )
#rmdir删除目录,需要先清空文件中的子目录或文件夹
#removedirs可多层删除目录(需要目录中无文件) makedirs可多层创建目录
if (os.path.isdir( "./os" )) :
os.rmdir( "./os" )
#删除文件
if (os.path.exists( './tpm.txt' )):
os.remove( './tpm.txt' )
|
os模块中常用方法和属性:
属性 os.linesep 文件中分割行的字符串 os.sep文件路径名的分隔符 os.curdir当前工作目录的字符串名称 os.pardir父目录字符串名称 方法 os.remove()删除文件 os.rename()重命名文件 os.walk()生成目录树下的所有文件名 os.chdir()改变目录 os.mkdir/makedirs创建目录/多层目录 os.rmdir/removedirs删除目录/多层目录 listdir()列出指定目录的文件 getcwd()取得当前工作目录(current work directory) chmod()改变目录权限 os.path.basename()去掉目录路径,返回文件名 os.path.dirname()去掉文件名,返回目录路径 os.path.join()将分离的各部分组合成一个路径名 os.path.split()返回(dirname(),basename())元组 os.path.splitext()(返回filename,extension)元组 os.path.getatime\ctime\mtime分别返回最近访问、创建、修改时间 os.path.getsize()返回文件大小 os.path.exists()是否存在 os.path.isabs()是否为绝对路径 os.path.isdir()是否为目录 os.path.isfile()是否为文件
4、文件目录操作(shutil包)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 |
import os
import shutil
#复制文件,相当于CP命令
shutil.copy( 'start2.txt' , 'start3' )
#移动文件或目录,相当于MV命令
shutil.move( 'start3' , 'start4' )
if (os.path.exists( './a/b/c' ) = = False ) :
os.makedirs( './a/b/c' )
#删除目录
shutil.rmtree( './a' )
if (os.path.exists( './a/b/c/d' ) = = False ) :
os.makedirs( './a/b/c/d' )
#复制目录
if (os.path.exists( 'b' ) = = False ) :
shutil.copytree( 'a' , 'b' )
|
shutil中常用方法
copyfile( src, dst) 从源src复制到dst中去。当然前提是目标地址是具备可写权限。抛出的异常信息为IOException. 如果当前的dst已存在的话就会被覆盖掉 copymode( src, dst) 只是会复制其权限其他的东西是不会被复制的 copystat( src, dst) 复制权限、最后访问时间、最后修改时间 copy( src, dst) 复制一个文件到一个文件或一个目录 copy2( src, dst) 在copy上的基础上再复制文件最后访问时间与修改时间也复制过来了,类似于cp –p的东西 copy2( src, dst) 如果两个位置的文件系统是一样的话相当于是rename操作,只是改名;如果是不在相同的文件系统的话就是做move操作 copytree(olddir,newdir,True/Flase) 把olddir拷贝一份newdir,如果第3个参数是True,则复制目录时将保持文件夹下的符号连接,如果第3个参数是False,则将在复制的目录下生成物理副本来替代符号连接 rmtree(path[, ignore_errors[, onerror]]) 删除目录 move( src, dst) 移动文件或目录
5、应用 - 遍历文件夹
1
2
3
4
5
6
7
8
9
10 |
import os
#遍历当前路劲下的所有目录和文件夹
#返回元组包含三个参数:1.父目录 2.所有文件夹名字(不含路径) 3.所有文件名字
for root, dirs, files in os.walk(os.getcwd()):
#输出文件夹信息
for dir in dirs:
print (os.path.join(root, dir ))
#输出文件信息
for file in files:
print (os.path.join(root, file ))
|
6、总结
Python的文件操作和PHP类似,都有现成的函数去实现,所以基本上记住常用的函数就可以了。
--EOF-- 除非注明,博客文章均为原创,转载请以链接形式标明本文地址 本文地址: http:///python-file.html
|