首页 热点资讯 义务教育 高等教育 出国留学 考研考公
您的当前位置:首页正文

python 读写文件

2024-12-21 来源:花图问答

读文件

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)
显示全文