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 Truepath = join(current,subPath)if isdir(path):dirs.append(path)return False
print(search('G:\\study\\Python','excel.txt'))
效果圖如下: