2022国赛33:linux编写python3脚本
大赛试题内容:
九、脚本(10分)
在Linux4上编写/root/CreateFile.py的python3脚本,创建20个文件/root/test/File01至/root/test/File20,如果文件存在,则先删除再创建;每个文件的内容同文件名,如File01文件的内容为“File01”。
解答过程:
1、安装
[root@cs4 ~]#yum -y install python36
2、创建目录
[root@cs4 ~]#mkdir test
3、编写脚本
[root@cs4 ~]#vi CreateFile.py
import os,shutil
for a in range(0,20):
b = \'%02d\' % a
Filename = \'/root/test/File\' +str(b)
if os.path.exists(Filename):
print(Filename +\'文件已存在\')
os.remove(Filename)
print(Filename +\'文件已删除\')
with open(Filename,\'w\') as NR:
NR.write(\"File\" + str(b))
print(Filename +\'文件已创建\')
保存退出。
4、运行脚本
[root@cs14~]# python3 CreateFile.py
/root/test/File00文件已创建