零基础学python-3.7 还有一个程序 python读写文本

今天我们引入另外一个程序,文件的读写

我们先把简单的程序代码贴上。然后通过我们多次的改进。希望最后可以变成一个简单的文本编辑器

以下是我们最简单的代码:

'crudfile--读写文件'
def readWholeFile(fileName):
    '读取整个文件'
    file = open(fileName, mode='r')
    text = []
    for eachLine in file:
        print(eachLine)
        text.append(eachLine)
    return text

def writeFile(fileName):
    '写文件'
    handler = open(fileName, mode='w')
    while True:
        inputText = input('>')
        if inputText == 'exit':
            break
        else:
            handler.write(inputText) 
try:
    fileName = "test.txt"
    writeFile(fileName);
    textInFile = readWholeFile(fileName);
except IOError as e:
    print(e)
    print('文件不存在')


 

原文地址:https://www.cnblogs.com/mthoutai/p/6846268.html