如何创建具有不同打印语句的不同txt文件?

问题描述 投票:0回答:1

我在执行此代码分配时遇到了很多麻烦。我目前正在尝试做的是为婚礼请柬创建单独的文件。我想做的是为每个新打印的声明/邀请创建一个新的 txt 文件。以下是我一直在尝试做的事情,目前我无法将每个打印语句放入具有新文件名的新 txt 文件中。

import os
if os.path.isfile("guest_list.txt"):
     # Open files for input
     infile = open("guest_list.txt", "r")

     line = infile.readline() # Read a line
     while line != '': # read until end-of-file
         e = open("event_details.txt","r")
         splitLine = line.split()
         letter = print("Dear,", splitLine[0],"",splitLine[1],"\n" \
                        "With great pleasure we are delighted to invite you to our wedding.\n" \
                        "We would be honored if you and your family could save the date.\n",e.read())
         w = open("wedding_invite.txt","w")
         w.write(''.join("Dear",str(splitLine[0]),"",str(splitLine[1])))
         w.write("With great pleasure we are delighted to invite you to our wedding.")
         w.write(''.join("We would be honored if you and your family could save the date.\n",e.read()))              
                        
         #read next line
         line = infile.readline() # Read next line from file
         e.close()
         w.close()
     infile.close()
python file-io
1个回答
0
投票

您在每次迭代中都会覆盖文件

wedding_invite.txt

您想为每位客人创建一个新的 .txt 文件:

import os
if os.path.isfile("guest_list.txt"):
    #read all the guest names into a list
    with open("guest_list.txt", "r") as infile:
        #read all the guest names to a list
        guest_list = infile.read().strip().split("\n")
    
    #read the event_details file just once instead of in each loop
    with open("event_details.txt") as infile:
        date = infile.read().strip()
    
    #loop through the guest_list and create custom invitations
    for line in guest_list:
         words = line.split(" ")
         #create new file for each guest
         with open(f"{line}.txt", "w") as outfile:
            outfile.write(f"Dear {words[0]} {words[1]},\n")
            outfile.write("With great pleasure we are delighted to invite you to our wedding.\n")
            outfile.write(f"We would be honored if you and your family could save the date.\n{date}")
© www.soinside.com 2019 - 2024. All rights reserved.