简体   繁体   中英

Python: 1) How to reference two string variables and insert a list element in between? 2) How can I append the string constructed to a list?

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!

I hope this works for you...

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

fp = open('MiddlePhrase.txt','r')
#reads each line
for i in fp:
    # getting string of desired format.
    text = firstPhrase+i.strip()+secondPhrase+'\n'
    #storing it in NewPhraseFile.txt
    with open("NewPhraseFile.txt",'a') as new:
        new.write(text)
    new.close()

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!

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'))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM