列表的LIFO与文件交互

礼拜的LIFO特性:

LIFO(Last In First Out)

其实就是堆栈功能,比如搭积木:

第一块在最下面,最后一块在最上面,拆的时候总是最后一块先拆,以此类推(stack)

代码实现:

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import sys

LIFO = []

def view():
    print(LIFO)

def push(a):
    LIFO.append(a)
    view()

def pop():
    LIFO.pop()
    view()


def quit():
    sys.exit()

while True:
    choose = input("Please choose one button
{push,pop,view,quit}
>:")
    choose = choose.upper()
    if choose == "PUSH":
        val = input("Enter something
>:")
        push(val)
    elif choose == "POP":
        pop()
    elif choose == "VIEW":
        view()
    else:
        quit()

允许用户创建文件与写入内容

代码:

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
'makefile.py -- create text file'

import os ; import sys
ls = os.linesep

#循环要求输入文件名

while True:
    fname = input("Enter a filename(fullname): ")
    if os.path.exists(fname):
        print("ERROR '%s' is already exists!" % fname)
    else:
        break

#获取文件内容
all = []

print("
 enter  lines('q' by itself to quit)")

while True:
    content = input('> ')
    if content.lower() == 'q':
        break
    else:
        all.append(content)

#写入文件

with open(fname, 'w') as fobj:
    fobj.writelines(['%s%s' % (x, ls) for x in all])

print:"Done"
原文地址:https://www.cnblogs.com/alben-cisco/p/6959968.html