zoukankan      html  css  js  c++  java
  • Python 文件IO:TXT 文件的读取与写入

    原文链接:https://blog.xieqiaokang.com/posts/36031.html

    读取

    使用 open() 函数配合 rt 模式读取文本文件内容:

    备注1:rt 模式中的 t 表示对换行符进行智能转换,在 UNIX 和 Windows 中换行符的识别是不同的,对于 UNIX 换行符为 ,而 Windows 为 。默认情况下,Python 工作在“通用型换行符”模式下,可以将所有常见的换行格式识别出来。加入 t 参数,在读取时,如果换行符为 ,会将其转换为 字符。同理,在写入时会将换行符 转换为当前系统默认的换行符。

    备注2:也可以给 open() 函数提供一个 newline='' 参数对换行符进行手动操作。

    # 将整个文件读取为一个字符串
    with open('file.txt', 'rt') as f:
        data = f.read()
        
    # 一行一行地读取文件
    with open('file.txt', 'rt') as f:
        for line in f:
            # process line
            ...
    

    备注:使用 with 语句,会为使用的文件创建一个上下文环境,当程序的控制流程离开 with 语句块后,文件将自动关闭。如果不使用 with 语句,需记得手动关闭文件:f.close()

    举例:将 .txt 文件内容读取为一个 python 列表,列表元素按顺序依次为文本文件每一行的内容:

    def read_txt(txt_path):
        lines = []
        with open(txt_path, 'rt') as f:
            for line in f:
                lines.append(line.strip())
        return lines
    

    写入

    与读取类似,使用 wt 模式即可。

    # 将文本内容写入文件
    with open('file.txt', 'wt') as f:
        f.write(line_1)
        f.write(line_2)
        ...
        
    # 将 print() 输出重定向到文件
    with open('file.txt', 'wt') as f:
        print(line_1, file=f)
        print(line_2, file=f)
        ...
    
  • 相关阅读:
    以太坊:深入理解Solidity-Solidity v0.5.0 重大更新
    以太坊:深入理解Solidity-合约
    以太坊:深入理解Solidity-表达式和控制结构
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
    我的友情链接
  • 原文地址:https://www.cnblogs.com/xieqk/p/python-txt-IO-read-write.html
Copyright © 2011-2022 走看看