案例6:操作文件系统
• 编写脚本,熟悉os模块操作
1. 切换到/tmp目录
2. 创建example目录
3. 切换到/tmp/example目录
4. 创建test文件,并写入字符串foo bar
5. 列出/tmp/exaple目录内容
6. 打印test文件内容
7. 反向操作,把test文件以及example目录删除
import os
os.getcwd() # 显示当前路径
os.listdir() # ls -a
os.listdir('/tmp') # ls -a /tmp
os.mkdir('/tmp/mydemo') # mkdir /tmp/mydemo
os.chdir('/tmp/mydemo') # cd /tmp/mydemo
os.listdir()
os.mknod('test.txt') # touch test.txt
os.symlink('/etc/hosts', 'zhuji') # ln -s /etc/hosts zhuji
os.path.isfile('test.txt') # 判断test.txt是不是文件
os.path.islink('zhuji') # 判断zhuji是不是软链接
os.path.isdir('/etc')
os.path.exists('/tmp') # 判断是否存在
os.path.basename('/tmp/abc/aaa.txt')
os.path.dirname('/tmp/abc/aaa.txt')
os.path.split('/tmp/abc/aaa.txt')
os.path.join('/home/tom', 'xyz.txt')
import getpass
userdb = {}
def register():
username = input('username: ')
if username in userdb:
print('%s already exists.' % username)
else:
password = input('password: ')
userdb[username] = password
def login():
username = input('username: ')
password = getpass.getpass("password: ")
if userdb.get(username) != password:
print('login failed')
else:
print('login successful')
def show_menu():
cmds = {'0': register, '1': login}
prompt = """(0) register
(1) login
(2) exit
Please input your choice(0/1/2): """
while True:
choice = input(prompt).strip()[0]
if choice not in '012':
print('Invalid inupt. Try again.')
continue
if choice == '2':
break
cmds[choice]()
if __name__ == '__main__':
show_menu()