读书人

python汉语言本文件处理

发布时间: 2012-09-09 09:27:54 作者: rapoo

python中文本文件处理

1.文本文件的读取

import fileinputprint("-----start-----")file = open("D:\\test.txt", encoding="utf-8")#打印出文件中的每一行数据isreadable = Truewhile isreadable == True :    data = file.readline()    if data != "":        print(data)    else:        isreadable = Falsefile.seek(0)print(file.readlines())file.close()with open("D:\\test.txt", encoding="utf-8") as data1:    for oneLine in data1:        print(oneLine)

?
*打开文件使用内置函数open(),使用文件名和字符编码作为参数,并返回一个流对象。
*readline()可以读取文件中的一行,seek()可以定位到文件中的特定字节。
*with创建了一个运行时环境,当退出这个运行时环境时会调用流对象的close()方法。

?

2.文本文件的写入

import fileinputfile = open("D:\\test.txt", encoding="utf-8",mode="w")file.write("朝八晚十\n")file.close()with open("D:\\test.txt", encoding="utf-8",mode="a") as data:    data.write("朝九晚五")

?*mode="w",写模式,会重写文件;mode="a",追加模式,会在文件末尾添加数据。

读书人网 >perl python

热点推荐