>>> f = open('D:/python/学习资料/record.txt',encoding = 'utf-8')
>>> f.read(5)
'噫吁嚱,危'
>>> f.tell()
15
>>> f.seek(0,0)
0
>>> f.readline()
'噫吁嚱,危乎高哉!\n'
>>> for eachline in f:
print(eachline)
噫吁嚱,危乎高哉!
蜀道之难,难于上青天!
蚕丛及鱼凫,开国何茫然!
尔来四万八千岁,不与秦塞通人烟。
西当太白有鸟道,可以横绝峨眉巅。
地崩山摧壮士死,然后天梯石栈相钩连。
上有六龙回日之高标,下有冲波逆折之回川。
黄鹤之飞尚不得过,猿猱欲度愁攀援。
青泥何盘盘,百步九折萦岩峦。
扪参历井仰胁息,以手抚膺坐长叹。
>>> f = open('D:/python/学习资料/test.txt','w',encoding = 'utf-8')
>>> f.write('i love you')
10
>>> f.close()
一个课堂任务
def save_file(boy,girl,count):
file_name_boy = 'boy' + str(count) + '.txt'
file_name_girl = 'girl' + str(count) + '.txt'
boy_file = open(file_name_boy,'w')
girl_file = open(file_name_girl,'w')
boy_file.writelines(boy)
girl_file.writelines(girl)
boy_file.close()
girl_file.close()
def split_file():
f = open('D:/python/学习资料/record.txt',encoding = 'utf-8')
boy = []
girl = []
count = 1
for each_line in f :
if each_line[:6] != '======':
(role,line_spoken) = each_line.split(':',1)
print(line_spoken)
if role == '小甲鱼':
boy.append(line_spoken)
if role == '小客服':
girl.append(line_spoken)
else:
save_file(boy,girl,count)
boy = []
girl = []
count += 1
save_file(boy,girl,count)
f.close()
split_file()
接受输入并保存为新文件
file_name = input('请输入文件名:')
f = open(file_name,'x')
contend = input('请输入内容【单独输入'':w''保存退出】:')
f.write(contend)
f.write('\n')
while contend != ':w':
contend = input()
f.write(contend)
f.write('\n')
f.close()
比较两个文件的不同
file_name1 = input('请输入需要比较的头一个文件名:')
file_name2 = input('请输入需要比较的另一个文件名:')
f1 = open(file_name1,'r')
f2 = open(file_name2,'r',encoding = 'utf-8')
f2 = list(f2)
count = 0
number = 0
for each_line in f1:
if f2[count] != each_line:
count += 1
print('第%d行不一样' % count)
count -= 1
number += 1
count += 1
print('两个文件共有【' , number , '】处不同')
输出文件前几行
file_name = input('请输入要打开的文件名:')
count = int(input('请输入要显示的文件前几行:'))
f1 = open(file_name,'r')
for each_line in f1:
print(each_line)
count -= 1
if count == 0:
break
输出指定的行数
file_name = input('请输入要打开的文件名:')
f1 = open(file_name,'r')
f1 = list(f1)
display = input('请输入要显示的行数:(例如2:4或:4或6:或:)')
(start,end) = display.split(':',1)
if start == '':
start = 1
else:
start = int(start)
if end == '':
end = len(f1)
else:
end = int(end)
if start == 1 and end != len(f1):
print('从开始到第%d行的内容如下:' % end)
elif start != 1 and end == len(f1):
print('从第%d到末尾的内容如下:' % start)
elif start == 1 and end == len(f1):
print('全文的内容如下:')
else:
print('从第%d行到第%d行的内容如下:' % (start , end))
for each_line in range(start,end+1):
print(f1[each_line-1])