欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用python读写取本地文件

程序员文章站 2022-05-29 16:49:30
...
# -*- codeing = utf-8 -*-
# @Time : 2021/3/13 2:26 下午
# @Author : Lixin
# @File : day32.py
# @Software : PyCharm

#ancientPoetry变量中是文本内容
ancientPoetry = """
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
"""
#写文件的方法
def fileWrite(content,fileName):
    try:
        txtFile = open(fileName, "w")
        try:
            txtFile.writelines(content)
            print("写入完毕")
        finally:
            txtFile.close()
            print("关闭文件")
    except Exception as e:
        print("写入文件出现异常,原因为:",e)
#读文件的方法
def fileRead(fileName):
    try:
        txtFile = open(fileName, "r")
        try:
            print("读取完毕")
            return txtFile.readlines()
        finally:
            txtFile.close()
            print("关闭文件")
    except Exception as e:
        print("读取文件出现异常,原因为:",e)
fileWrite(ancientPoetry,"ancientPoetry.txt")
read = fileRead("ancientPoetry.txt")
if read:
    fileWrite(read,"copy.txt")
    print("复制成功")
else:
    print("复制失败")