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

python文件操作实例

2013-02-07 19:38 666 查看

python文件操作实例

来源:岁月联盟 编辑:exp
时间:2012-09-14

[align=center][/align]
[python]

# -*- coding: utf-8 -*-

import os

import shutil

# 一. 路径操作:判断、获取和删除

#1. 得到当前工作目录,即当前Python脚本工作的目录路径: os.getcwd()

#print: currentpath: f:/LearnPython

currentpath = os.getcwd()

print "currentpath: ",currentpath

#2. 返回指定目录下的所有文件和目录名:os.listdir()

#print:os.listdir(): ['test.txt', 'testRW.py', 'test1.txt', 'cmd.py', 'rwfile.py', 'downloadfile.py', 'date.py', 'time.py', 'datetime.py', 'file.py']

print "os.listdir(): ",os.listdir('f:/LearnPython')

path = "F:/mmmmmmmmm/debug_taobao_200003@taobao_android1.6_3.2.1.apk"

#3. 判断给出的路径是否真地存:os.path.exists()

if os.path.exists(path):

#删除一个文件:os.remove()

os.remove(path)

else:

print path,"not exist"

#4. 删除多个目录:os.removedirs(“c:/python”)

#它只能删除空目录,如果目录里面有内容将不会被删除

if os.path.exists("d:/woqu"):

os.removedirs("d:/woqu")

else:

os.mkdir("d:/woqu")

os.removedirs("d:/woqu")

#5. 判断给出的路径是否是一个文件:os.path.isfile()

#print: True

print os.path.isfile("D:/hello/json.txt")

#6. 判断给出的路径是否是一个目录:os.path.isdir()

#print: True

print os.path.isdir("D:/hello")

#7. 判断是否是绝对路径:os.path.isabs()

#print: True

print os.path.isabs("D:/hello")

# 判断是否是链接

print os.path.islink('http://www.baidu.com')

#8. 返回一个路径的目录名和文件名:os.path.split()

#eg os.path.split('/home/swaroop/byte/code/poem.txt') 结果:('/home/swaroop/byte/code', 'poem.txt')

#print: ('D://hello', 'json.txt')

print os.path.split("D:/hello/json.txt")

#9. 分离扩展名:os.path.splitext()

#print:('D://hello//json', '.txt')

print os.path.splitext("D:/hello/json.txt")

#10. 获取路径名:os.path.dirname()

#print: 'D://hello'

print os.path.dirname("D:/hello/json.txt")

#11. 获取文件名:os.path.basename()

#print: 'json.txt'

print os.path.basename("D:/hello/json.txt")

#13. 指示你正在使用的平台:os.name 对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'

print "os.name: ",os.name

#14. linex 下的命令

if os.name == 'posix':

#读取和设置环境变量:os.getenv() 与os.putenv()

home_path = os.environ['HOME']

home_path = os.getenv('HOME') #读取环境变量 

elif os.name == 'nt':

home_path = 'd:'

print 'home_path: ',home_path

#15. 给出当前平台使用的行终止符:os.linesep Windows使用'/r/n',Linux使用'/n'而Mac使用'/r'

print(os.linesep)

#16. 应为windows和linux的路径有点点不一样,windows是用 // 来分割的,linux是用 / 来分隔,

#而用os.sep 会自动根据系统选择用哪个分隔符。

print(os.sep)

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

#先进入目录

os.chdir("d://hello")

print os.getcwd()

#18. 再重命名

os.rename("1.txt", "11.txt")

#19. 创建多级目录:os.makedirs(“c:/python/test”)

os.makedirs('d:/h/e/l/l/o')

#20. 创建单个目录:os.mkdir(“test”)

os.mkdir('d:/f')

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

#print: nt.stat_result(st_mode=33206, st_ino=0L, st_dev=0, st_nlink=0, st_uid=0, st_gid=0, st_size=497L, st_atime=1346688000L, st_mtime=1346748054L, st_ctime=1346748052L)

print os.stat('d:/hello/json.txt')

#22. 修改文件权限与时间戳:os.chmod(path,mode)

#这里有介绍:http://blog.csdn.net/wirelessqa/article/details/7974477

#23. 终止当前进程:os.exit()

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

print os.path.getsize('d:/hello/json.txt')

文件操作:

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") 换路径

实例:将文件夹下所有图片名称加上'_once-ler'

[python]

# -*- coding:utf-8 -*-

import re

import os

import time

#str.split(string)分割字符串

#'连接符'.join(list) 将列表组成字符串

def file_changename(filepath):

global picnum

file_path = os.path.split(filepath) #分割出目录与文件

lists = file_path[1].split('.') #分割出文件与文件扩展名

file_ext = lists[-1] #取出后缀名(列表切片操作)

img_ext = ['bmp','jpeg','gif','psd','png','jpg']

if file_ext in img_ext:

os.rename(filepath,file_path[0]+'/'+lists[0]+'_once-ler.'+file_ext)

picnum+=1

def change_name(path):

if not os.path.isdir(path) and not os.path.isfile(path):

return False

elif os.path.isfile(path):

file_changename(path)

elif os.path.isdir(path):

for x in os.listdir(path):

print 'os.path.join(path,x): ',os.path.join(path,x)

file_changename(os.path.join(path,x))

#os.path.join()在路径处理上很有用

if __name__ == '__main__':

img_dir = 'D://hello//capture'

print img_dir

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

print img_dir

start = time.time()

print start

picnum = 0

change_name(img_dir)

spenttime = time.time() - start

print('程序运行耗时:%0.2f'%(spenttime))

print('总共处理了 %s 张图片'%(picnum))

下面这个文件运行有错误,摘自:http://rsjy.org/2023.html

[python]

#!/usr/bin/python

# -*- coding:utf-8 -*-

import os

# 定义几个函数

def del_file(wpath):

os.remove(wpath) # 删除文件

def del_dir(wpath):

os.removedirs(wpath) # 删除空文件夹

def gen_dir(wpath):

if os.path.exists(wpath):

pass

else:

os.mkdir(wpath) # 建立文件夹

def gen_file(wpath):

if os.path.exists(wpath):

pass

else:

os.mknod(wpath) # 建立文件

print(os.sep)

print(os.linesep) # 字符串给出当前平台使用的行终止符

# print(os.environ)

if os.name == 'posix':

home_path = os.environ['HOME']

home_path = os.getenv('HOME') #读取环境变量 

elif os.name == 'nt':

home_path = 'd:' # win 下未测试

# 定义进行测试的文件夹与文件的名称

tep_dir = 'xx_tep'

tep_dir_a = 'tep_dir_a'

tep_dir_b = 'tep_dir_b'

tep_file_a = 'tep_file_a.txt'

tep_file_b = 'tep_file_b.py'

tep_file_c = 'tep_file_c.c'

# 合成文件夹与文件的全路径

path_tep = os.path.join(home_path, tep_dir)

path_dir_a = os.path.join(path_tep, tep_dir_a)

path_dir_b = os.path.join(path_tep, tep_dir_b)

path_file_a = os.path.join(path_dir_a, tep_file_a)

path_file_b = os.path.join(path_dir_a, tep_file_b)

path_file_c = os.path.join(path_dir_b, tep_file_c)

# 在系统内生成相应的文件夹与文件

gen_dir(path_tep)

gen_dir(path_dir_a)

gen_dir(path_dir_b)

gen_file(path_file_a)

gen_file(path_file_b)

gen_file(path_file_c)

cwd = os.getcwd() # 得到当前工作目录,即当前Python脚本工作的目录路径。

wlist = os.listdir(cwd)

for wli in wlist:

print(wli)

os.chdir(path_tep) # 切换路径

cwd = os.getcwd() # 得到当前工作目录,即当前Python脚本工作的目录路径。

wlist = os.listdir(cwd)

for wli in wlist:

print(wli)

if os.path.isdir(path_dir_a): # 判断是否文件夹

tep_size = os.path.getsize(path_dir_a)

print(tep_size)

if os.path.isfile(path_file_a):

tep_size = os.path.getsize(path_file_a) # 获得文件大小

print(tep_size)

for wroot, wdirs, wfiles in os.walk(path_tep):

for wfile in wfiles:

file_path = os.path.abspath(wfile) # 获得绝对路径

print(file_path)

# 返回文件名

filename = os.path.basename(path_file_a)

print(filename)

# 返回文件路径

dirname = os.path.dirname(path_file_a)

print(dirname)

# 分割文件名与目录

# 事实上,如果你完全使用目录,它也会将最后一个目录作为文件名而分离,

# 同时它不会判断文件或目录是否存在

(filepath, filename) = os.path.split(path_file_a)

print(filepath, filename)

(fname, fext) = os.path.splitext(filename) # 分离文件名与扩展名

print(fname, fext)

# 清理文件与文件夹

del_file(path_file_a)

del_file(path_file_b)

del_dir(path_dir_a)

del_file(path_file_c)

del_dir(path_dir_b)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: