Python_文本操作

 1 #向文本文件中写入内容
 2 s='Hello world\n文本文件的读取方法\n文本文件的写入方法\n'
 3 f=open('sample1.txt','a+')   #打开文件
 4 f.write(s)  #写入文件内容
 5 f.close()   #关闭文件
 6 
 7 with open('sample1.txt','a+') as f:
 8     f.write(s)
 9 
10 #上下文管理语句with还支持下面的用法:
11 with open('test.txt','r')as src,open('test_new.txt','w')as dst:
12     dst.write(src.read())
13 
14 for line in open('test.txt'):
15     print(line)
16 
17 #读取文本文件内容
18 fp = open('test.txt')
19 # test.txt内的内容g4a6d4g6a5gaojdfoiayufiajgldjuaidfjldakjgalgm ladjglfa98epofajiidfjladjfajf
20 print(fp.read(4))   #从当前位置读取前4个字符
21 # g4a6
22 print(fp.read(18))  #英文制作字幕和汉字一样对待
23 # d4g6a5gaojdfoiayuf
24 #文本文件的读取方法
25 print(fp.read())    #从当前位置读取后面的所有内容
26 # iajgldjuaidfjldakjgalgm ladjglfa98epofajiidfjladjfajf
27 #文本文件的写入方法
28 fp.close()  #关闭文件对象
 1 '''
 2 读取并显示文本文件的所有行,文件对象是可迭代的
 3 '''
 4 with open('sample.txt') as fp:
 5     print(type(fp))
 6     while True:
 7         line=fp.readline()
 8         if not line:
 9             break
10         print(line)
11 
12 
13 with open('sample.txt') as fp:
14     for line in fp: #文件对象是可以迭代的
15         print(line)
16 
17 with open('sample.txt') as fp:
18     lines = fp.readlines()  #操作大文件时不建议这么做
19     print(''.join(lines))
20 
21 '''
22 移动文件指针。假设文件sampple.txt中的内容原为'Hello world\n文本文件的读取方法\n文本文件的写入方法'
23 '''
24 fp =open('sample.txt','r+')
25 print(fp.tell())  #返回文件指针的当前位置
26 # 0
27 print(fp.read(20)) #读取20个字符
28 #  属虎2017年几岁:
29 # 属虎
30 #   201
31 fp.seek(13) #重新丁文文件指针位置
32 print(fp.read(5))
33 # 年几岁:
34 fp.seek(100)
35 fp.write('测试移动')
36 fp.flush()  #把缓冲区内容写入磁盘文件
37 fp.seek(0)
38 print(fp.read())
39 fp.close()

备注:出现的文本文件自行创建

posted @ 2017-06-10 14:57  JustLittle  阅读(317)  评论(0编辑  收藏  举报