2022 National Competition 33: Write python3 scripts in linux

Contest content:

9. Screenplay (10 minutes)

Write the python3 script of /root/CreateFile.py on Linux4, create 20 files /root/test/File01 to /root/test/File20, if the file exists, delete it first and then create it; the content of each file is the same as the file name , such as the content of the File01 file is "File01".

Solution process:

1. Installation

[root@cs4 ~]#yum -y install python36

2. Create a directory

[root@cs4 ~]#mkdir test

3. Write the script

[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 +'file already exists')
       os.remove(Filename)
       print(Filename + 'file removed')
    with open(Filename,'w') as NR:
        NR.write("File" + str(b))
        print(Filename + 'file created')

Save and exit.

4. Run the script

[root@cs14~]# python3 CreateFile.py

/root/test/File00 file created

Guess you like

Origin blog.csdn.net/weixin_41687096/article/details/130196239