Reputation: 533
I have a .txt file that contain as below:
text line1
text line2
text line3
.
.
text line n
I am trying to insert a char $ to the start and end of each line, I should get like this:
$text line1$
$text line2$
$text line3$
.
.
$text line n$
my code is :
Read_data = open("finename.txt","r")
text_line = Read_data.readline()
while text_line:
text_line = '$' + text_line + '$'
Write_data = open('newfile.txt', 'a')
Write_data.write(text_line)
text_line = Read_data.readline()
Write_data.close()
the output I got like this :
$text line1
$$text line2
$$text line3
.
.
.
$$text line n
$
any idea why getting that ?
Upvotes: 2
Views: 231
Reputation: 533
I am correcting @Vladir Parrado Cruz using while loop instead of for loop, coz with for loop you will get different output:
Read_data = open("finename.txt","r")
Write_data = open('newfile.txt', 'a')
text_line = Read_data.readline()
while text_line:
text_line = '$' + text_line.strip() + '$\n'
Write_data.write(text_line)
text_line = Read_data.readline()
Write_data.close()
Upvotes: 1
Reputation: 1705
You need to open both files outside the loop, then loop over the available input lines. Something like this:
Read_data = open("finename.txt","r")
Write_data = open('newfile.txt', 'a')
for text_line in Read_data.readlines():
formatted_text_line = '$' + text_line + '$'
Write_data.write(formatted_text_line)
Write_data.close()
You may also need to add a newline to the written line to get what you want:
formatted_text_line = '$' + text_line + '$\n'
Upvotes: 1
Reputation: 2359
Remember that you need to strip the \n
character on each line. Check this post Python Add string to each line in a file.
This should work for your code (following the suggestion of opening the files outside the loop):
Read_data = open("finename.txt","r")
Write_data = open('newfile.txt', 'a')
for text_line in Read_data.readline():
text_line = '$' + text_line.strip() + '$\n'
Write_data.write(text_line)
Write_data.close()
Upvotes: 4
Reputation: 29007
Your problem is that text
has a trailing newline character, and you are putting the $ after it. Try:
text = '$' + text[:-1] + '$\n'
Upvotes: 2