0

Here is a .txt file (semi colon signifies start of file):

MiddlePhrase.txt:
coke and cheeseburgers
bread and wine
beer and tacos

Here is the code I have now:

middlePhrases = open('MiddlePhrase.txt', 'r')

firstPhrase = 'I love to drink and eat '
secondPhrase = ' when I am at the beach!'

for i in middlePhrases:
    print(beginningPhrase,{},endPhrase)

The goal is to write the first line of 'MiddlePhrase.txt' to a new .txt file named 'NewPhraseFile.txt', then append the following two lines in 'MiddlePhrase.txt' to the 'NewPhraseFile.txt'

This is the desired output (a new .txt file being written with content):

NewPhraseFile.txt:
I love to drink and eat coke and cheeseburgers when I am at the beach!
I love to drink and eat bread and wine when I am at the beach!
I love to drink and eat beer and tacos when I am at the beach!
5
  • can you show the code you have tried? Commented Dec 19, 2021 at 6:48
  • Please edit the post with your attempt at solving the question. Commented Dec 19, 2021 at 6:48
  • Okay, give me a minute to edit it! Thanks. Commented Dec 19, 2021 at 6:49
  • Have you tried something? Please add your code snippet and tell the problem with your code. Commented Dec 19, 2021 at 6:49
  • I have updated the question with more relevant code! Commented Dec 19, 2021 at 6:53

2 Answers 2

2

A short version

open('new.txt', 'a+').writelines(
    f'I love to drink and eat {x.strip()} when I am at the beach!\n'
    for x in open('mid.txt'))
Sign up to request clarification or add additional context in comments.

1 Comment

Woah mama! Nice code! fire emoji
1

I hope this works for you...

firstPhrase = 'I love to drink and eat '
secondPhrase = ' when I am at the beach!'
with open('MiddlePhrase.txt', 'r') as middlePhrases, open('NewPhraseFile.txt', 'a') as newPhrases:
    for phrase in middlePhrases:
        middlePhrase = phrase.strip()
        newPhrases.write(firstPhrase + middlePhrase + secondPhrase + '\n')

Output in NewPhraseFile.txt:

I love to drink and eat coke and cheeseburger when I am at the beach!
I love to drink and eat bread and wine when I am at the beach!
I love to drink and eat beer and tacos when I am at the beach!

2 Comments

Awesome code! Thank you. Happy holidays!
you don't need to close the file new as with will automatically handle that for you. you need to close fp though, as you are not using with there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.