《云计算全栈》-python篇:系统模块、操作文件系统

案例6:操作文件系统
9.1 问题

创建os_module.py脚本,熟悉os模块操作,要求如下:

切换到/tmp目录
创建example目录
切换到/tmp/example目录
创建test文件,并写入字符串foo bar
列出/tmp/exaple目录内容
打印test文件内容
反向操作,把test文件以及example目录删除

      
      
      
      
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

9.2 方案

用os方法查看用户当前所在位置,切换到指定目录,创建example目录,切换到创建目录下,以读写方式打开并创建一个新文件,将指定内容写入新文件中,列出目录下有指定目录下有哪些文件,指定从开始位置读取指定文件字符串并打印出来,关闭打开文件,并删除文件,删除目录。

注意:读取打印文件内容时,要将字节转化为字符串读取出来。
9.3 步骤

实现此案例需要按照如下步骤进行。

步骤一:编写脚本

    [root@localhost day05]# vim os_module.py
    #!/usr/bin/env python3
    import os
    #1)    切换到/tmp目录
    os.getcwd()        #'/root/python代码/os'
    os.chdir("/tmp") 
    os.getcwd()        #'/tmp'
    #2)    创建example目录 
    os.mkdir("example")
    #3)    切换到/tmp/example目录
    os.chdir("/tmp/example")
    os.getcwd()        #'/tmp/example' 
    #4)    创建test文件,并写入字符串foo bar
    f=os.open("test.txt",os.O_RDWR|os.O_CREAT)        #以读写方式打开/创建并打开一个新文件
    os.write(f,b"foo bar nihao")
    #5)    列出/tmp/exaple目录内容
    os.listdir("/tmp/example")     #['test.txt']
    #6)    打印test文件内容 
    os.lseek(f,0,0)        #指定从开始位置读取字符串
    str=os.read(f,100)
    str = bytes.decode(str)
    print("读取的字符是:",str)
    os.close(f)
    #7)    反向操作,把test文件以及example目录删除
    os.remove("/tmp/example/test.txt")
    os.removedirs("/tmp/example")

      
      
      
      
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26

步骤二:测试脚本执行

[root@localhost day05]# python3 os_module.py 
读取的字符是: foo bar

      
      
      
      
  • 1
  • 2
                                
发布了404 篇原创文章 · 获赞 56 · 访问量 4万+

你可能感兴趣的:(linux运维开发基础)