前面讨论了好多读,写,复制等文件的操作方式。现在,来一个大集合。
紫色的标注是需要注意的部分。很容易出错。带'---'的表示是提示用的文字。
蓝色的标注分别表示代码的6个部分。函数,读,写,复制,移动,删除。(函数部分的作
用是为了代替if语句中需要重复输入的代码)。
值得注意的是,os.remove专门删除文件。shut.rmtree()则是专门删除目录/文件夹。在删除
和移动某文件前切记要关闭已打开的该文件。
# coding: utf-8
import os
from os.path import exists # 有了这一句,就不用再写os.path.exists()了,直接exists()
print "(^-o^o-^) w: 'write'; r: 'read'; 'c': copy; 'd': delete"
respond = raw_input(">>> ")
# 函数区
# 写入文件或者创建新文件
def InputFile():
print "----------Input the filename please!----------"
filename = raw_input("filename: ")
# 注意这里的filename已经是变量, 不能再加引号了
txt = open(filename, 'a+')
# 注意这里若无return,无法提取函数中的变量。因为本身函数中的变量是独立于外面代码区的。
return filename, txt
# 返回上一步操作
def Return():
print "(^-0-0-^) Ok, now rechoose the module..."
print "(^-o^o-^) w: 'write'; r: 'read'; 'c': copy; 'd': delete"
respond = raw_input(">>> ")
return respond
# 询问是否返回上一步操作
def IfContinue():
print "If continue? 'n' to back or any key to continue!"
choose = raw_input(">>> ")
if 'n' in choose:
Return()
else:
print "Ok, let's continue..."
# 写入文件
if 'w' in respond:
# 判断文件是否存在
print u"(-o<O>o-) 启动读写模式"
IfContinue()
# 前面说了,return是为了利用函数中的变量 。返回的值超过两个。即是以元组的形式存在。
# 元组也和列表一样,是有顺序的。
w = InputFile()
filename = w[0]
txt = w[1]
print txt
print "----------Does the file exists? %s----------" % exists(filename)
if exists(filename) == True:
print "----------Open the file: %s ----------\n" % filename
# 调整指针, 记得一定要在write()之后,read()之前
txt.seek(0)
print txt
print txt.read()
# 是否清空文件
print "----------Do you want to empty it?!!!----------"
empty = raw_input(">>> ")
if 'y' in empty:
print "----------File has already empty...---------"
txt = open(filename, 'w')
else:
print "----------Ok, next action...----------"
elif exists(filename) == False:
print "----------The file '%s' is created----------"
# 由于while True是无限循环,所以用CTRL+C去中断输入
print "----------Write down something-----------"
print "----------Type Ctrl + C to save----------"
# 写入任意行
n = 0
while True:
n += 1
content = raw_input("Line %s: " % n)
txt.write(content + '\n')
# 读取文件
elif 'r' in respond:
print u"(<o0.0o>) 启动读取模式"
IfContinue()
r = InputFile()
filename = r[0]
txt = r[1]
print "----------Open the file: %s----------" % filename
print txt
txt.seek(0)
print txt.read()
# 复制文件
elif 'c' in respond:
print u"(-0o0-) 进入复制模式"
IfContinue()
c = InputFile()
filename = c[0]
txt = c[1]
content = txt.read()
print "Input the number you want to copy!"
number = int(raw_input("number: "))
# 这样就可以输入中文文件名了,先解码成标准码'utf-8',再编码成汉字用的内码'gbk'
filename = raw_input('filename: '.decode('utf-8').encode('gbk'))
# 创建目录,移动文件
# 新建一个目录/文件夹, 把我们新建的文件都放到夹子里面去
if exists(filename) == True:
print sys.path[0] + filename
print u"目录已存在"
else:
os.mkdir(filename) # 这一段蓝色的代码就避免了存在同名文件夹filename而再重建发生错误的情况
for i in range(1, number): # 同名的文件夹不能重复建立,它不像open()可以重复打开但还是同个文件
to_file = '%s(%d).txt' % (filename, i)
to_txt = open(to_file, 'w')
to_txt.write(content)
# 此处如果不关闭文件的话,和os.remove()的一样,绝对会报错到你哭:WindowsError
to_txt.close()
shutil.move(to_txt, filename) # to_txt表示文件,filename表示新建的文件夹
# 删除文件
elif 'd' in respond:
print u"(-1——0>>>) 删除模式"
print u"删除某个文件——请按1,批量删除指定文件——请按2"
choose = raw_input('digital : ')
if choose == '1':
IfContinue()
d = InputFile()
filename = d[0]
txt = d[1]
# 如果不关闭文件的话,无法删除,会提示系统错误
txt.close()
print "Do you want to delete it?"
answer = raw_input(">>> ")
if 'n' in answer:
print "----------Ok, skip it...----------"
print "----------Do you have other file to delete?----------"
else:
print "----------File has already empty!----------"
os.remove(filename)
print "----------Do you have other file to deal?----------"
answer = raw_input(">>> ")
if 'n' in answer:
print "Exit the script..."
else:
print u"(^-Q~Q-^)现在进入重复删除模式"
print "----------Type CTRL + C to stop...--------- "
# 重复删除
while True:
file = raw_input(">>> ")
print "...Deal..."
os.remove(file)
elif choose == '2':
print "----------Please offer the postfix----------"
# 输入后缀名/扩展名
postfix = raw_input("")
currdir = 'c:\\python27\\5.19code\\test'
# 批量删除指定后缀名的文件
def RemoveFile(dir, postfix):
if os.path.isdir(dir):
for file in os.listdir(dir):
RemoveFile(dir + "\\" + file, postfix)
elif os.path.splitext(dir)[1] == postfix:
os.remove(dir)
RemoveFile(currdir, postfix)
print "Ok, files have been deleted!"
else:
print "Exit the script!"
上面的'gbk'是国标扩展码,也就是中文简体字用的内码。'utf'是unicode转换格式。
再次提醒:无论是删除os.remove()还是移动文件shutil.move(),在此之前一定要关闭文件