文件建立

“# -- coding: utf-8 --” 有这句才可以编码中文

#文件建立
#!/usr/bin/python
# -*- coding: utf-8 -*-
f = open('text2.txt','w')

文件写入

#文件写入
f.write('Love is patient,\n' 'love is kind.\n' 'It does not envy,\n' 'it does not boast,\n' 'it is not proud.\n')
f.close()

文件读取

f.read()

#文件读取1-read()
f = open('text2.txt','r')
content = f.read(5)
print(content) # Love 五个字符算空格
content = f.read(5)
print(content) # is pa 不是每次都从头开始读的
f.close()

f.readlines()

# 文件读取2-readlines()
f = open('text2.txt','r')
content = f.readlines() #0 也一样
print(content) #打印所有
f = open('text2.txt','r')
content = f.readlines(2) #1,2,3,4,5 ...
print(content) # ['Love is patient,\n'] 打印第1行,无论输入什么都只打印第一行
f = open('text2.txt','r')
content = f.readlines()
i = 1
for temp in content:
    print("%d:%s"%(i,temp),end='') #加行号
    i += 1 
'''
1:Love is patient,
2:love is kind.
3:It does not envy,
4:it does not boast,
5:it is not proud.
'''
f.close()

f.readline()

# 文件读取3-readline()
f = open('text2.txt','r')
content = f.readline()
print('1:%s'%content,end='') # 1:Love is patient,
content = f.readline()
print('2:%s'%content,end='') # 2:love is kind.
content = f.readline()
print(content,end='') # It does not envy,
f.close()
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐