《零基础入门学习Python》第029讲:文件:一个任务

目录

0. 请写下这一节课你学习到的内容:格式不限,回忆并复述是加强记忆的好方式!

任务:将文件(record.txt)中的数据进行分割并按照以下规律保存起来:

–小甲鱼的对话单独保存为boy_*.txt的文件(去掉“小甲鱼:”)

–小客服的对话单独保存为girl_*.txt的文件(去掉“小客服:”)

–文件中总共有三段对话,分别保存为boy_1.txt, girl_1.txt,boy_2.txt, girl_2.txt, boy_3.txt, gril_3.txt共6个文件(提示:文件中不同的对话间已经使用“==========”分割)

小客服:小甲鱼,今天有客户问你有没有女朋友?
小甲鱼:咦??
小客服:我跟她说你有女朋友了!
小甲鱼:。。。。。。
小客服:她让你分手后考虑下她!然后我说:"您要买个优盘,我就帮您留意下~"
小甲鱼:然后呢?
小客服:她买了两个,说发一个货就好~
小甲鱼:呃。。。。。。你真牛!
小客服:那是,谁让我是鱼C最可爱小客服嘛~
小甲鱼:下次有人想调戏你我不阻止~
小客服:滚!!!
================================================================================
小客服:小甲鱼,有个好评很好笑哈。
小甲鱼:哦?
小客服:"有了小甲鱼,以后妈妈再也不用担心我的学习了~"
小甲鱼:哈哈哈,我看到丫,我还发微博了呢~
小客服:嗯嗯,我看了你的微博丫~
小甲鱼:哟西~
小客服:那个有条回复“左手拿著小甲魚,右手拿著打火機,哪裡不會點哪裡,so easy ^_^”
小甲鱼:T_T
================================================================================
小客服:小甲鱼,今天一个会员想找你
小甲鱼:哦?什么事?
小客服:他说你一个学生月薪已经超过12k了!!
小甲鱼:哪里的?
小客服:上海的
小甲鱼:那正常,哪家公司?
小客服:他没说呀。
小甲鱼:哦
小客服:老大,为什么我工资那么低啊??是时候涨涨工资了!!
小甲鱼:啊,你说什么?我在外边呢,这里好吵吖。。。。。。
小客服:滚!!!

 

f = open('record.txt')
 
boy = []
girl = []
count = 1
 
for each_line in f:
    if each_line[:6] != '======':
        (role, line_spoken) = each_line.split(':', 1)
        if role == '小甲鱼':
            boy.append(line_spoken)
        if role == '小客服':
            girl.append(line_spoken)
    else:
        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()
 
        boy = []
        girl = []
        count += 1
 
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()
 
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(file_name):
    f = open(file_name)
 
    boy = []
    girl = []
    count = 1
 
    for each_line in f:
        if each_line[:6] != '======':
            (role, line_spoken) = each_line.split(':', 1)
            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('record.txt')


 

0. 编写一个程序,接受用户的输入并保存为新的文件,程序实现如图:

def write_file(file_name):
    f = open(file_name,'w',encoding = 'utf-8')
    print('请输入内容【单独输入\':w\'保存退出】:')

    while True:
        write_some = input()
        if write_some != ':w':
            f.write('%s\n' % write_some)
        else:
            break
    f.close()

file_name = input('请输入文件名:')
write_file(file_name)

1. 编写一个程序,比较用户输入的两个文件,如果不同,显示出所有不同处的行号与第一个不同字符的位置,程序实现如图:

不封装: 

#!/usr/bin/env python 
# -*- coding:utf-8 -*-

file1 = input('请输入需要比较的头一个文件名:')
file2 = input('请输入需要比较的另一个文件名:')
f1 = open(file1, encoding='utf-8')
f2 = open(file2, encoding='utf-8')
count = 0  # 统计行数
differ = []  # 统计不一样的数量
ide = []

for line1 in f1:
    line2 = f2.readline()
    count += 1
    if line1 != line2:
        differ.append(count)

        for i in range(len(line1)):
            if line1[i]!=line2[i]:

                i += 1
                ide.append(i)
                break

f1.close()
f2.close()



if len(differ) == 0:
    print('两个文件完全一样!')
else:
    print('两个文件共有【%d】处不同:' % len(differ))
    for each ,i in zip(differ,ide):
        print('第%d行的第%d处不一样' % (each,i))
        print('内容是:\n%s%s'%(line1,line2))



封装: 

#!/usr/bin/env python 
# -*- coding:utf-8 -*-

def file_compare(file1, file2):
    f1 = open(file1, encoding='utf-8')
    f2 = open(file2, encoding='utf-8')
    count = 0  # 统计行数
    differ = []  # 统计不一样的数量
    ide = []
    content = []

    for line1 in f1:
        line2 = f2.readline()
        count += 1
        if line1 != line2:
            # print(line1,line2)
            differ.append(count)
            content.append((line1,line2))


            for i in range(len(line1)):
                if line1[i] != line2[i]:
                    i += 1
                    ide.append(i)
                    break

    f1.close()
    f2.close()
    return zip(differ, ide,content)


file1 = input('请输入需要比较的头一个文件名:')
file2 = input('请输入需要比较的另一个文件名:')

duu = file_compare(file1, file2)
differ,ide,content = zip(*duu)

if len(differ) == 0:
    print('两个文件完全一样!')
else:
    print('两个文件共有【%d】处不同:' % len(differ))
    for each ,i,c in zip(differ,ide,content):
        print('第%d行的第%d处不一样,内容是:\n%s%s' % (each,i,c[0],c[1]))

2. 编写一个程序,当用户输入文件名和行数(N)后,将该文件的前N行内容打印到屏幕上,程序实现如图:

def file_view(file_name, line_num):
    print('\n文件%s的前%s的内容如下:\n' % (file_name, line_num))
    f = open(file_name,encoding='utf-8')
    for i in range(int(line_num)):
        print(f.readline(), end='')

    f.close()


file_name = input(r'请输入要打开的文件(C:\\test.txt):')
line_num = input('请输入需要显示该文件前几行:')
file_view(file_name, line_num)

 

3. 呃,不得不说我们的用户变得越来越刁钻了。要求在上一题的基础上扩展,用户可以随意输入需要显示的行数。

 

def file_view(file_name, line_num):
     if line_num.strip() == ':':
         begin = '1'
         end = '-1'

    (begin, end) = line_num.split(':')
    print((begin, end))

    if begin == '':
        begin = '1'
    if end == '':
        end = '-1'

    if begin == '1' and end == '-1':
        prompt = '的全文'
    elif begin == '1':
        prompt = '从开始到%s' % end
    elif end == '-1':
        prompt = '从%s到结束' % begin
    else:
        prompt = '从第%s行到第%s行' % (begin, end)

    print('\n文件%s%s的内容如下:\n' % (file_name, prompt))

    begin = int(begin) - 1
    end = int(end)
    lines = end - begin

    f = open(file_name,encoding='utf-8')

    for i in range(begin):  # 用于消耗掉begin之前的内容
        #f.readline()
        print(f.readline())

    if lines < 0:
        print(f.read())
    else:
        for j in range(lines):
            print(f.readline(), end='')

    f.close()


file_name = input(r'请输入要打开的文件(C:\\test.txt):')
line_num = input('请输入需要显示的行数【格式如 13:21 或 :21 或 21: 或 : 】:')
file_view(file_name, line_num)

 

4. 编写一个程序,实现“全部替换”功能,程序实现如图:

#!/usr/bin/env python 
# -*- coding:utf-8 -*-

def instead_file(file_name,instead_word,new_word):
    f = open(file_name,encoding='utf-8')

    content = []
    count = 0

    for each_line in f:
        if instead_word in each_line:
            count += 1
            each_line = each_line.replace(instead_word,new_word)
        content.append(each_line)

    decide = input('\n文件 %s 中共有%s个【%s】\n您确定要把所有的【%s】替换为【%s】吗? \n【YES/NO】:'\
                   %(file_name,count,instead_word,instead_word,new_word))

    if decide.upper() == 'YES':
        f_write = open(file_name,'w',encoding='utf-8')
        f_write.writelines(content)
        f_write.close()

    f.close()

file_name = input('请输入文件名:')
instead_word = input('请输入需要替换的字符:')
new_word = input('请输入新字符:')
instead_file(file_name,instead_word,new_word)

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值