【文件操作】读写文本文件

【读写txt文件】

r:只读

w:只写模式【不可读;不存在则创建;存在则清空内容】

w+:w+,写读【可读,可写】,消除文件内容,然后以读写方式打开文件。

#coding=utf-8

# 读文件
def read_file():

    # 读取文件
    read_txt = open('txt/read_txt','r')

    # 一次读取一行
    oneline = read_txt.readline()
    print('oneline:\n',oneline)

    # 一次读取所有行【接着上一条读取结束往下读】
    for line in read_txt.readlines():
        print('lines:\n',line)

    # 一次读取所有【接着上一条读取的往下读】
    all = read_txt.read()
    print('all:\n',all)

    read_txt.close()
read_file()

# 写文件
def write_file():
    # w:只写模式【不可读;不存在则创建;存在则清空内容】
    write_txt = open('txt/write_txt','w',encoding='utf-8')
    write_txt.write('hello\nnihao')
    write_txt.write('你好')

    # w+,写读【可读,可写】,消除文件内容,然后以读写方式打开文件。
    write_txt2 = open('txt/write_txt2','w+',encoding='utf-8')
    write_txt2.writelines('writelines:你好')
    write_txt2.writelines('writelines:hello')

    write_txt.close()
    write_txt2.close()
write_file()

 

posted @ 2017-12-20 15:43  白小白001  阅读(366)  评论(0编辑  收藏  举报