python-文件处理小练习

创建一个程序可以根据用户的输入对文件进行读或者写操作,不管读或写,都需要用户手动输入文件名。
在读操作中,如果文件读取成功,需要打印文件内容,在写操作中,使用追写模式添加任意内容后,
打印修改后的文件内容即可。(注意,要对可能出现的异常进行处理,并在最后将文件关闭)

import os
while True:
    name = input('请输入要创建的文件名:')
    if os.path.exists(name):
        print('该文件已经存在,请重新定义文件名!')
        continue
    else:
        with open(name,'a+',encoding='utf-8') as file:
            choice = int(input('请选择要操作的内容:(读:1/写:2)'))
            if choice == 1:
                if file != '':
                    print('该文档还没有内容!')
                else:
                    print(file.read())
            else:
                while True:
                    Write = input('请输入要写入的内容:')
                    file.write(Write)
                    file.write('\n')
                    file.read()
                    z=input('输入完毕!是否要再次输入内容?(y/n)')
                    if z=='y':
                        Write = input('请输入要写入的内容:')
                        file.write(Write)
                        file.read()
                    else:
                        break

猜你喜欢

转载自blog.csdn.net/liaozp88/article/details/120815135
今日推荐