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

【Python/PE】python中实现文件操作的几种功能(删除指定目录下的所有内容,文件复制等)

2018-01-14 17:11 2306 查看
###Date: 2018/1/14

###Author:SoaringLee

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


1、文件操作功能1:清空指定目录(很有用哦)

# -*- coding: cp936 -*-
import os
import shutil

def DelAllInDir(dir):
for dirpath, dirnames, filenames in os.walk(dir):
#print dirpath
#print dirnames
for filename in filenames:#删除当前目录下的所有文件
if  os.path.isfile(os.path.join(dirpath,filename)):
os.remove(os.path.join(dirpath,filename))
print os.path.join(dirpath,filename)

for dirname in dirnames:#遍历所有的子目录
print dirname
if os.path.isdir(os.path.join(dirpath,dirname)):
DelAllInDir(os.path.join(dirpath,dirname))#删除当前目录下子目录中的所有文件
os.rmdir(os.path.join(dirpath))#清空目录(该函数只能用于删除空目录)

if __name__=='__main__':
if len(os.sys.argv)<2:
print "Usage: delAllInDir.py dir"
dir =  os.sys.argv[1]
DelAllInDir(dir)
主要功能函数:os.walk(),os.remove(),os.path.join()

2、文件操作功能2:复制指定目录文件

def copyFiles(sourceDir,  targetDir):
for file in os.listdir(sourceDir):
sourceFile = os.path.join(sourceDir,  file)
targetFile = os.path.join(targetDir,  file)
if os.path.isfile(sourceFile):
if not os.path.exists(targetDir):
os.makedirs(targetDir)
if not os.path.exists(targetFile) or (os.path.exists(targetFile) and (os.path.getsize(targetFile) != os.path.getsize(sourceFile))):
open(targetFile, "wb").write(open(sourceFile, "rb").read())
if os.path.isdir(sourceFile):
copyFiles(sourceFile, targetFile)

主要功能函数:os.makedirs(),os.path.exists(),open(),write(),read()

3、文件操作功能3:批量修改文件名

import os

def RenameFiles(srcdir):
#将目录下所有的文件命名为数字开头的名称
srcfiles = os.listdir(srcdir)
index = 1
for srcfile in srcfiles:
print srcfile
sufix = os.path.splitext(srcfile)[1]
print sufix
destfile = srcdir + "//" + u"%d"%(index) + sufix
srcfile = os.path.join(srcdir, srcfile)
os.rename(srcfile, destfile)
index += 1
srcdir = u"奥运"
RenameFiles(srcdir)

主要功能函数:os.listdir(),os.path.splitext(),os.rename()


4、文件操作功能4:文件复制操作的两种方法

#coding:utf-8

# 方法1:使用read()和write()模拟实现文件拷贝

# 创建文件hello.txt
src = file("hello.txt", "w")
li = ["Hello world \n", "Hello China \n"]

src.writelines(li)
src.close()

#把hello.txt 拷贝到hello2.txt

src = file("hello.txt", "r")
dst = file("hello2.txt", "w")

dst.write(src.read())##重点哦

src.close()
dst.close()

# 方法2:使用shutil模块
# shutil模块是一个文件、目录的管理接口,提供了一些用于复制文件、目录的函数
# copyfile()函数可以实现文件的拷贝
# copyfile(src, dst)
# move()函数实现文件的剪切
# move(src, dst)

import shutil

shutil.copyfile("hello.txt", "hello2.txt")    #hello.txt内容复制给hello2.txt
shutil.move("hello.txt", "../")              #hello.txt复制到当前目录的父目录,然后删除hello.txt
shutil.move("hello2.txt", "hello3.txt")      #hello2.txt移到当前目录并命名为hello3.py, 然后删除hello2.txt
主要功能函数:write(),read(),shutil.copyfile(),shutil.move()


参考:

https://www.cnblogs.com/rgtv-wilkins/p/4358179.html
https://www.cnblogs.com/sld666666/archive/2011/01/05/1926282.html http://blog.csdn.net/henryghx/article/details/49227345
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐