头歌实践平台(Educoder):Python 文件处理教学案例十二
第1关 读取唐诗文件,并根据诗人建立多个文件夹
import os
import shutil
if os.path.exists("wjcl/src/step4/tssr"):
shutil.rmtree("wjcl/src/step4/tssr")
os.mkdir("wjcl/src/step4/tssr")
f1=open("wjcl/src/step1/唐诗.txt",'r')
#代码开始
for line in f1:
if line[:3].isdigit():
a=line[3:line.find(":")]
b="wjcl/src/step4/tssr//"+a
if not os.path.isdir(b):
os.mkdir(b)
f1.close()
#代码结束
第2关 读取唐诗文件,根据诗人建立多个文件
import shutil
import os
if os.path.exists("wjcl/src/step3/ts"):
shutil.rmtree("wjcl/src/step3/ts")
os.mkdir("wjcl/src/step3/ts")
f1=open("wjcl/src/step1/唐诗.txt",'r')
#代码开始
for line in f1:
if line[:3].isdigit():
srxm=line[3:line.find(":")]
wj="wjcl/src/step3/ts/"+srxm+".txt"
f2=open(wj,"a")
if len(line.strip())>0:
f2.write(line)
#代码结束
f1.close()
f2.close()
第3关 读取唐诗文件,为每首诗建立文本文件
import os
import shutil
if os.path.exists("wjcl/src/step5/ts"):
shutil.rmtree("wjcl/src/step5/ts")
os.mkdir("wjcl/src/step5/ts")
f1=open("wjcl/src/step1/唐诗.txt",'r')
#代码开始
for line in f1:
if line[:3].isdigit():
a=line[3:line.find(":")]
c=line[line.find(":")+1:].strip()
d="wjcl/src/step5/ts/"+a
if not os.path.exists(d):
os.mkdir(d)
b="wjcl/src/step5/ts/"+a+"/"+c+".txt"
f2=open(b,"a")
f2.write(c+"\n")
f2.write(a+"\n")
elif len(line.strip())>0:
f2.write(line)
f1.close()
f2.close()
#代码结束
第4关 文件的复制文件的复制
import os
import shutil
lj="wjcl/src/素材"
lj1="wjcl/素材"
if os.path.exists(lj):
shutil.rmtree(lj)
shutil.copytree(lj1,lj)
#代码开始
a=lj+"/风景图片"
if not os.path.exists(a):
os.mkdir(a)
b=os.listdir(lj1)
for x in b:
if os.path.isdir(lj1+"/"+x) and x!="风景图片"and x!=".gitkeep":
c=0
y=os.listdir(lj1+"/"+x)
for i in y:
ywj=lj1+"/"+x+"/"+i
if os.path.splitext(i)[-1]==".jpg":
c+=1
xwj=a+"/"+x+str(c)+".jpg"
shutil.copyfile(ywj,xwj)
#代码结束
ml=os.listdir(lj+"/风景图片")
ml.sort()
for x in ml:
print(x)
第5关 选择题
1、若a.txt文件已经存在,并已经有多行文本 下列哪个语句可以打开a.txt,并在文本后追加helloworld ( A )
A、
f1=open("a.txt","a") f1.write("helloworld") f1.close()
B、
f1=open("a.txt","w") f1.write("helloworld") f1.close()
C、
f1=open("a.txt","r") f1.write("helloworld") f1.close()
D、
f1=open("a.txt","x") f1.write("helloworld") f1.close()
2、os库中建立文件夹的命令是 ( B )
A、
rmdir
B、
mkdir
C、
chdir
D、
listdir
3、文件dat.txt里的内容如下:
QQ&Wechat&Google &Baidu
以下程序的输出结果是:( D )
fo = open("tet.txt",'r')
fo.seek(2)
print(fo.read(7))
fo.close()
A、Wechat
B、QQ&Wech
C、Wechat&
D、&Wechat
4、若需要在当前文件夹的上级文件夹下建立一个a.txt文件(此文件目前不存在) 将26个字母写入文件 以下正确的命令是 ( C )
A、f1=open("..\\a.txt","w")
f1.write("abcdefghijklmnopqrstuvwxyz")
B、f1=open("..\\a.txt")
f1.write("abcdefghijklmnopqrstuvwxyz")
f1.close()
C、f1=open("../a.txt","a")
f1.write("abcdefghijklmnopqrstuvwxyz")
f1.close()
D、f1=open("a.txt","x")
f1.write("abcdefghijklmnopqrstuvwxyz")
f1.close()
5、若需要将当前文件夹下的image文件夹(所有文件和子文件夹),复制到d盘的2021文件夹下,应该使用下列哪组命令 ( D )
os.system("copy images\\*.* d:\\2021")
B、import os
os.system("move images\\*.* d:\\2021")
C、import os
shutil.copyfile('images' ,'c:/2021')
D、import os
shutil.copytree('images' ,'c:/2021/images')
作者:Yu_Meng~