python⽂件和⽬录操作题库1. 把⼀个⽬录下所有的⽂件删除,在所有的⽬录下新建⼀个a.txt的⽂件,并在⽂件下写⼊"python"关键字。解题思路:
1.如果⽬录存在则切换进⼊⽬录
2.遍历⽬录下所有的⽂件和⽬录
3.判断如果是⽂件就删除,如果是⽬录则在⽬录下新建⼀个a.txt⽂件,并把"python"写⼊⽂件。
解题⽅法:
#⽅法⼀:
#encoding=utf-8
import os
import os.path
def HandFile():
if ists("e:\\test"):
os.chdir("e:\\test")
file_list=os.wd())
for i in file_list:
#查看test⽬录下的所有⽂件和⽬录
#print (i)
#判断如果是⽂件,则删除;是⽬录则获取⽬录的绝对路径,写⽂件到⽬录下。
if os.path.isfile(i):
else:
#获取⽬录的绝对路径
path_name=os.path.abspath(i)
#print("path_name:",path_name)
#写⽂件到⽬录
with open(path_name+"\\a.txt","w") as fp:
fp.write("python\n")
else:
print("FileNotFoundError!")
HandFile()
#⽅法⼆:
#encoding=utf-8
import os
import os.path
def HandFile():
if ists("e:\\test"):
os.chdir("e:\\test")
for i in os.listdir("e:\\test"):  #os.listdir(".")
if os.path.isfile(i):
else:
#如果是⽬录,则切换进⼊⽬录
os.chdir(i)
fp=open("a.txt","w",encoding="utf-8")  #设置指定编码
fp.write("python\n")
fp.close()
os.chdir("..")  #返回单上级⽬录
else:
print("FileNotFoundError!")
HandFile()
#⽅法三:
#encoding=utf-8
import os
import os.path
def HandFile():
try:
os.chdir("e:\\test")
for i in os.listdir("e:\\test"):  #os.listdir(".")
if os.path.isfile(i):
else:
#获取⽬录的绝对路径
path_name=os.path.abspath(i)
#print("path_name:",path_name)
#写⽂件到⽬录
with open(path_name+"\\a.txt","w") as fp:
fp.write("python\n")
except FileNotFoundError:
print ("File Not Found!")
except:
python怎么读取桌面上的文件print ("Unknown error !")
HandFile()
注意点:对于判断⽬录e:\\test是否存在的问题,如果⽬录存在则切换进⼊test⽬录,并且遍历⽬录。如果不存在,则直接进⾏处理异常。
以下是错误代码⽰例:
if ists("e:\\test"):
os.chdir("e:\\test")
for i in os.wd()):
if os.path.isfile(i):
else:
with open(os.path.abspath(i)+"\\a.txt","w") as fp:
fp.write("python\n")
如果test⽬录不存在,程序继续往下执⾏,遍历当前操作⽬录,本⼈默认当前操作⽬录是计算机桌⾯也就是desktop,这时候悲催的⼀幕发⽣了,我的桌⾯所有的⽂件都被⼲掉了,且不可恢复,相当于执⾏了delete操作。