美文网首页
python 读写文件

python 读写文件

作者: 滴滴时光 | 来源:发表于2017-07-24 10:29 被阅读3次

读文件

def read_file(filepath):
    with open(filepath, 'r', encoding='utf-8') as file:
        for line in file:
            print(line)

写文件

def write_file(filepath):
    with open(filepath, 'w', encoding='utf-8') as file:
        file.write('hello world')

读写文件

def read_write_file(filepath):
    with open(filepath, 'r+', encoding='utf-8') as file:
        text = file.read()
        # 处理文本
        text = re.sub('python', 'python3', text)
        # 默认是在最后追加,以下方法可覆盖
        file.seek(0)
        file.truncate()
        # 写入
        file.write(text)

https://stackoverflow.com/a/13464228/3355097

相关文章

网友评论

      本文标题:python 读写文件

      本文链接:https://www.haomeiwen.com/subject/ignvkxtx.html