`
拓子轩
  • 浏览: 205622 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

python中文本文件处理

阅读更多

1.文本文件的读取

import fileinput

print("-----start-----")
file = open("D:\\test.txt", encoding="utf-8")

#打印出文件中的每一行数据
isreadable = True
while isreadable == True :
    data = file.readline()
    if data != "":
        print(data)
    else:
        isreadable = False

file.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 fileinput

file = 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",追加模式,会在文件末尾添加数据。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics