批量复制和删除
1. 说是从一个文件复制到另一个文件,
其实还是读写啦,参考:习题—17
http://www.2cto.com/shouce/Pythonbbf/index.html
# coding: utf-8
from sys import argv # 导入argv模块
from os.path import exists
script, from_file, to_file = argv # 将argv解包给script, from_file, to_file三个参数
print ">>>Copying from %s to %s." % (from_file, to_file)
from_txt = open(from_file)
content = from_txt.read()
print "...The file has %s bytes." % len(content) # len()用于查询字符串长度, 1个字母占1个字节
print ">>>Does the output file exist? %r" % exists(to_file)
print "...If you want to continue, hit Enter, or not, hit Ctrl+C."
raw_input("> ")
to_txt = open(to_file, 'w') # 以'w'写的模式打开,原有内容会被清空
to_txt.write(content)
print "Copy has done...and eixt!"
from_txt.close()
to_txt.close() # 有开就有关,记得关闭哦
---------------------------------------------------------------------------------------------------------
2. 利用 for循环 复制和删除多个 txt 文件
假设这个文件名赋值给了from_file变量
# coding: utf-8
from_txt = open('path') # path指文件所在的路径,比如c:\\python27\1.txt
content = from_txt.read()
for i in range(1, 101): # 将内容复制到新建的1.txt到100.txt等100个文本文件
to_file = "path\%d.txt" % i # path是文件所在路径。比如c:\python27\1.txt
to_txt = open(to_file, 'w') # %d是格式化字符串,可以用来替代十进制数
to_txt.write(content)
删除的话。 import os
蓝色换成 os.remove(to_file)
不过,这种删除的方法有很大的局限性,只能删除用循环建立的这种规律性较强的文件。
------------------------------------------------------------------------------------------
3. 用shutil.copy()或者shutil.copyfile()复制文件
前者是从文件到文件, 后者是从文件到文件或目录
# coding: utf-8
import shutil
for i in range(1 , 5):
to_file = "%s.txt" % i
shutil.copy(from_file, to_file)
------------------------------------------------------------------------------------------
4. 用递归算法删除.txt文件(这是路径还是统一用斜杠吧,因为下面也跟着用反斜杠的话还要转义)
# coding: utf-8
import os
currdir = 'c:/python27/5.19code/test' # current director当前目录。
# 我们所要删除的文件所在的目录即文件夹
def RemoveFile(dir, postfix): # dir这里是director目录即文件夹。当然变量可任意命名
if os.path.isdir(dir): # 判断是否为文件夹,是为True,否为False
for file in os.listdir(dir): # os.listfile会列出dir下所有的子文件和子文件夹,比如1.py, 1.txt
RemoveFile(dir + '/' + file, postfix) # 这里用了递归算法,就是在函数中重复使用同一个函数。
elif os.path.splitext(dir)[1] == postfix: # splitext()作用是将文件名分成前缀和后缀两部分。
os.remove(dir) # 输入代码import os (在编辑器中或在powershel中)
# print os.splitext('1.txt')
RemoveFile(currdir, '.txt') # 结果就是('1', '.txt'), 所以[1]位置1就是第二个元素
上面的路径若不想写成斜杠的形式,需要转义,'\\'才是表示'\', 而纯粹的'\'是续行符, 表示代码进入下一行
书写。所以要写成"c:\\python27\5.19code\\test"(或者掺入'/'也行), 只要记得反斜杠要转义就行了。
-----------------------------------------------------------------------------------------------------------
5. os.remove()只能删除文件。删除文件夹用shutil.rmtree()
# coding: utf-8
import shutil
shutil.copytree('oridir', 'desdir') # 删除之前先备份,original director是原文件,destination dir是目标文件名(新建)
shutil.rmtree('path') # 注意的是文件夹里面的所有内容,包括子文件和子文件夹
注意,shutil.rmtree()无法删除文件('.txt', '.zip'等),同样,shutil.copytree()也无法备份文件,只能是文件夹及其所有内容