Algorys
Algorys

Reputation: 1790

Add '\n' to each line of an open file in Python

I have something to send with mail in Python, and I want to add content file in the mail body.

The problem is to add '\n' to each line... I've make some tests but each time it puts the '\n' after each letter and not line...

Here is the file to add to mail (tests.new):

// Files Module
// Module Name
test.cpp
test2.cpp

And here is my script :

#!/usr/bin/env python3
newFile = open('tests.new','r')
tNew = newFile.read()
# mail
mail = open('mail.txt', 'w', encoding='utf8')
mail.write("New files in module \n")
# BAD PART
i = len(tNew)
z = 0
while z < i:
        mail.write(str(tNew[z].split('\n')))
        z += 1
        mail.close()

The end of the script (after #BAD PART) is one of the test I did. It's not obligate to follow this way...

If someone can help me please ?

Thanks

Upvotes: 0

Views: 1514

Answers (2)

Delimitry
Delimitry

Reputation: 3027

BAD PART problems:

1) tNew[z] returns single char, not the line. You need to get lines list first.

2) You close mail file in the loop and not open it again.

So the correct code must be:

#!/usr/bin/env python3
newFile = open('tests.new','r')
tNew = newFile.read()
# mail
mail = open('mail.txt', 'w', encoding='utf8')
mail.write("New files in module \n")

# BAD PART - FIXED
lines = tNew.split('\n')
i = len(lines)
z = 0
while z < i:
    mail.write(str(lines[z] + '\n'))
    z += 1
mail.close()
newFile.close()

But I'll recommend you to rewrite this code the more Pythonic way:

for line in tNew.split('\n'):
    mail.write(line + '\n')

Or better:

for line in open('tests.new', 'r'):
    mail.write(line + '\n')

And you'll not needed to use z counter, and i.

Upvotes: 0

RickyA
RickyA

Reputation: 16029

Your problem is newFile.read() reads the entire input file. You then iterate over it byte by byte in your while loop and append a newline after each char. Use the for line in newFile: stanza to iterate over lines in the inputfile.

Also your mail.close() is in an incorrect place. It is better to use the with open("somefile.txt") as ifile: stanza since that takes care of proper file closing after the block ends.

#!/usr/bin/env python3
with open('tests.new','r') as newFile: #this autocloses the file at the end of the block
    with open('mail.txt', 'w', encoding='utf8') as mail: #same
        mail.write("New files in module \n")
        for line in newFile: #iterate over lines in the inputfile instead of over characters
            mail.write("{}\n".format(line))

Upvotes: 3

Related Questions