• python cookboo 文件与IO 函数


    写出文本数据

    g = open('test.txt', 'rt', newline='',encoding = 'utf-8', errors='replace')

    t是windows平台特有的所谓text mode(文本模式),区别在于会自动识别windows平台的换行符。类Unix平台的换行符是 ,而windows平台用的是 两个ASCII字符来表示换行,python内部采用的是 来表示换行符。rt模式下,python在读取文本时会自动把 转换成 .wt模式下,Python写文件时会用 来表示换行。
    newline:在Unix和Windows中是不一样的(分别是n和rn)。 默认情况下,Python会以统一模式处理换行符。 这种模式下,在读取文本的时候,Python可以识别所有的普通换行符并将其转换为单个 字符类似的,在输出时会将换行符 转换为系统默认的换行符。 如果你不希望这种默认的处理方式,可以给open()函数传入参数newline=''
    encoding就是编码了
    errors=replace会忽略错误,比如如果encoding传ascii,在读的时候就有可能有错误,errors=replace会忽略所有错误的字符。

    打印输出到文件中

    print ('Hello World!', file = f)

    使用其他分隔符或换行符

      row = ('ACME', 50, 91.5
    # print(' '.join(row)) TypeError: sequence item 1: expected str instance, int found
    print (' '.join(str(x) for x in row))    #不需要这么麻烦,下面这样就可以了 print(*row, sep=' ', end='!!end')       #sep指定分隔符, end指定 以什么结束    ACME 50 91.5!!end

    文件不存在才写入

    f = open('txt', 'w')    #这么打开会覆盖原文件,如果原文件没有会新穿件
    f = open('txt', 'x')    #用x代替w,如果文件存在会报错。防止以为覆盖源文件
    #但是真正的解决办法是这个

      import os
      if not os . path . exists('somefile'):
        with open('somefile', 'wt') as f:
          f.write('Hello ')
      else:
        print('File already exists!')

    给函数添加元信息

    def add_test(x:int, y:int) -> int:
      print(x + y)
    add_test(x=1, y=2)
    print(add_test.__annotations__)        #{'y': <class 'int'>, 'return': <class 'int'>, 'x': <class 'int'>}
  • 相关阅读:
    CCPC-Wannafly Winter Camp Day4 Div1
    CCPC-Wannafly Winter Camp Day4 Div1
    CCPC-Wannafly Winter Camp Day4 Div1
    CCPC-Wannafly Winter Camp Day5 Div1
    Luogu 1603
    洛谷试炼场
    Codeforces 1100
    Codeforces 1099E
    Codeforces 1099
    Luogu 1093
  • 原文地址:https://www.cnblogs.com/badboyf/p/6653428.html
Copyright © 2020-2023  润新知