python3 文件操作

python3 文件操作

  • 读写文件

    1
    2
    3
    4
    5
    6
    7
    8

    with open('somefile.txt', 'rt') as f:
    data = f.read()


    text = 'some words'
    with open('somefile.txt', 'wt') as f:
    data = f.write(text)
  • 文件不存在才能写入

    可以在 open() 函数中使用 x 模式来代替 w 模式的方法来解决这个问题

    1
    2
    with open('somefile.txt', 'xt') as f:
    data = f.write('hello world!\n')