Python---实验八

1,现在有一份‘邀请函.txt’的空白文件,请在同级目录下编写一段代码,写入内容‘诚挚邀请您来参加本次宴会’。

with open(f'G:\study\Python\邀请函.txt',mode='w',encoding='utf-8') as y:
    y.write('诚挚邀请您来参加本次宴会')

效果图如下:
在这里插入图片描述

2,在第一题的基础上,添加上问候语和发件人,内容是’best regards 李雷’,让内容是:

诚挚邀请您来参加本次宴会。
best regards
李雷

with open(f'G:\study\Python\邀请函.txt',mode='w',encoding='utf-8') as y:
    y.write('诚挚邀请您来参加本次宴会。\nbest regards\n李雷')

效果图如下:
在这里插入图片描述

3,在第二题的基础上,这封邮件需要发送给‘丁一’、‘王美丽’、‘韩梅梅’三位朋友,请在邮件内容开头处添加收件人名字,并且生成相应名字的邮件。邮件内容应该为:

丁一:
诚挚邀请您来参加本次宴会
best regards
李雷

文件名为: 朋友姓名邀请函.txt

intimates = ['丁一','王美丽','韩梅梅']
with open('G:\study\Python\邀请函.txt',mode='r',encoding='utf-8') as y:
    includes = y.read()
    for intimate in intimates:
        with open('G:\study\Python\%s邀请函.txt'%intimate,mode='w',encoding='utf-8') as yy:
            yy.write('%s:\n'%intimate)
            yy.write(includes)

效果图如下:
在这里插入图片描述
在这里插入图片描述

4,使用嵌套循环实现九九乘法表,并将乘法表的内容写入到txt文件中。

with open('G:\study\Python\99乘法表.txt',mode='w',encoding='utf-8') as yy:
    for i in range(1,10):
        for j in range(1,i+1):
            yy.write('%d×%d=%-2d  '%(i,j,i*j))
        yy.write('\n')

效果图如下:
在这里插入图片描述

5,把记事本文件test.txt转换城Excel2007+文件。假设test.txt文件中第一行为表头,从第二行开始为实际数据,并且表头和数据行中的不同字段信息都是用逗号分隔。

from openpyxl import Workbook
def main(txtFileName):
    new_XlsxFileName = txtFileName[:-3] + 'xlsx'
    wb=Workbook()
    ws=wb.worksheets[0]
    with open(txtFileName,mode='r',encoding='utf-8') as y:
        for line in y:
            line = line.strip().split(',')
            ws.append(line)
    wb.save(new_XlsxFileName)
main('G:\\study\\Python\\excel.txt')

效果图如下:
在这里插入图片描述

6,编写程序,检查D:\文件夹及其子文件夹中是否存在一个名为temp.txt的文件。

from os import listdir
from os.path import join,isdir
def search(directory,fileName):
    dirs = [directory]
    print(dirs)
    while(dirs):
        current = dirs.pop(0)
        print(current)
        print(listdir(current))
        for subPath in listdir(current):
            if subPath == fileName:
                return True
            path = join(current,subPath)
            if isdir(path):
                dirs.append(path)
    return False
print(search('G:\\study\\Python','excel.txt'))

效果图如下:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_41264055/article/details/106087801