import os
import shutil
#SRC_DIR = 'E:\\zxl_work\\python\\test_os\\a\\'
#DST_DIR = 'E:\\zxl_work\\python\\test_os\\b\\'
SRC_DIR = r"E:\zxl_work\python\test_os\a"
DST_DIR = r"E:\zxl_work\python\test_os\b"
file_name_list = []
for parent,dir_names,file_names in os.walk(root_dir):
if file_names:
for file_name in file_names:
file_name_list.append(os.path.join(parent,file_name))
return file_name_list
def copy_file(src_dir, dst_dir):
if not os.access(src_dir, os.F_OK):
print '%s does not exist' %(src_dir)
#if not os.path.exists(dst_dir):
if not os.access(dst_dir, os.F_OK):
os.makedirs(dst_dir)
file_name_list = read_file_name(src_dir)
for src_file_name in file_name_list:
shutil.copy(src_file_name, dst_dir)
if __name__ == '__main__':
copy_file(SRC_DIR, DST_DIR)
在python程序里面我们经常需要对文件进行操作,Windows下的文件目录路径使用反斜杠“\”来分隔。但是,和大多数语言一样,Python代码里面,反斜杠“\”是转义符,例如“\n”表示回车、“\t”表示制表符等等。这样,如果继续用windows习惯使用“\”表示文件路径,就会产生歧义。
例如:“c:\test.txt”这表示c盘根目录下的一个文件,还是表示一个字符串呢?因为“\t”也可以解释为制表符。如果让我们人来判断,这当然是一个很简单的问题。但是机器就无法做出正确的判断了,只有没有歧义的代码机器才会正确执行。
解决办法,采用下面任何一种书写形式均可:
使用斜杠“/”: "c:/test.txt",不用反斜杠就没法产生歧义了
将反斜杠符号转义: "c:\\test.txt",因为反斜杠是转义符,所以两个"\\"就表示一个反斜杠符号
使用Python的raw string: r"c:\test.txt",python下在字符串前面加上字母r,表示后面是一个原始字符串raw string,不过raw string主要是为正则表达式而不是windows路径设计的,所以这种做法尽量少用,可能会出问题。
# coding=utf-8
import os
import shutil
SRC_DIR = r"E:\zxl_work\python\test_os\a"
DST_DIR = r"E:\zxl_work\python\test_os\b"
# 把某一目录下的所有文件复制到指定目录中
def copyFiles(sourceDir, targetDir):
if not os.access(sourceDir, os.F_OK):
print '%s does not exist' %(sourceDir)
return -1
if sourceDir.find(".svn") > 0:
return
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):
First_Directory = False
copyFiles(sourceFile, targetFile)
# 删除目录
def remove_dir(targetDir):
if not os.access(targetDir, os.F_OK):
print '%s does not exist' %(targetDir)
return -1
shutil.rmtree(targetDir)
if __name__ == '__main__':
copyFiles(SRC_DIR, DST_DIR)
remove_dir(DST_DIR)