简体   繁体   中英

Trying to insert a character $ for beginning and end of a string using python, but i got them just in the beginning

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 ?

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

Your problem is that text has a trailing newline character, and you are putting the $ after it. Try:

text = '$' + text[:-1] + '$\n'

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'

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

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