zoukankan      html  css  js  c++  java
  • python读写文件

    # python 文件读写,使用with避免try...finally的繁琐
    # 1、读取全部内容.文件太大可能会把内存爆了, 可用file.read(<字节数>)限制读取大小
    with open("test.txt", "r", encoding='utf8', errors='ignore') as file:
        print("1: ", file.read())
    # 2、按行读取,适合读取配置文件
    with open("test.txt", "r", encoding='utf8', errors='ignore') as file:
        for line in file.readlines():
            print("2: ", line.strip())
    # 3、写入文件-覆盖旧内容
    with open("test.txt", "w", encoding="utf8") as file:
        file.write("尼古拉斯.姚
    ")
    # 4、写入文件-追加
    with open("test.txt", "a", encoding="utf8") as file:
        file.write("尼古拉斯.姚
    ")
  • 相关阅读:
    两种方法生成随机字符串
    cmd命令总结
    NOI前乱写
    多校模拟9
    字符串 口胡
    HEOI2020游记
    省选模拟104
    省选模拟103
    省选模拟102
    省选模拟101
  • 原文地址:https://www.cnblogs.com/dannyyao/p/10000240.html
Copyright © 2011-2022 走看看