Home > Net >  How would I write separate words to a file, with words between them?
How would I write separate words to a file, with words between them?

Time:10-26

I am trying to write words from words.txt to newfile.txt using python3, with a format like this:

words.txt:

Hello
I
am
a
file

and I want the word Morning added between each new word in words.txt, inside a new file called newfile.txt.

so newfile.txt should look like this:

Hello
Morning
I
Morning
Am
Morning
A
Morning
File

Does anyone know how to do this?

Sorry about the bad phrasing, Gomenburu

CodePudding user response:

To avoid blowing main memory for a large file, you'd want to insert the extra strings as you go. It's not hard, just a little tricky to ensure they only go between existing lines, not at the beginning or end:

# Open both files
with open('words.txt') as inf, open('newfile.txt', 'w') as outf:
    outf.write(next(inf))        # Copy over first line without preceding "Morning"
    for line in inf:             # Lazily pull remaining lines from infile one by one
        outf.write("Morning\n")  # Write the in-between "Morning" before each new line
        outf.write(line)         # Write pre-existing line

CodePudding user response:

with open("words.txt", "r") as words_file, open("newfile.txt", "w") as new_words_file:
    new_words_file.write("\n".join([f"{word}\nMorning" for word in words_file.read().split("\n")]))

CodePudding user response:

with open('words.txt') as f:
lines = f.readlines()
for i in range(len(lines)):
    a = lines[i]   'Morning'   '\n'
    with open('newfile.txt','a') as file:
        file.write(a)
        file.close()

This should do it!

  • Related