python cookboo 文件与IO 函数

写出文本数据

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

t是windows平台特有的所谓text mode(文本模式),区别在于会自动识别windows平台的换行符。类Unix平台的换行符是\n,而windows平台用的是\r\n两个ASCII字符来表示换行,python内部采用的是\n来表示换行符。rt模式下,python在读取文本时会自动把\r\n转换成\n.wt模式下,Python写文件时会用\r\n来表示换行。
newline:在Unix和Windows中是不一样的(分别是n和rn)。 默认情况下,Python会以统一模式处理换行符。 这种模式下,在读取文本的时候,Python可以识别所有的普通换行符并将其转换为单个\n字符类似的,在输出时会将换行符\n转换为系统默认的换行符。 如果你不希望这种默认的处理方式,可以给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\n')
  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'>}

 

posted @ 2017-03-31 20:32  bad_boy_f  阅读(326)  评论(0编辑  收藏  举报