1

i have seen many other questions but it all shows how to remove all \n characters.

def copy_lines(input, output, c):

    with open("essay.txt","r") as f:
        with open("out.txt","w") as s:
            counter=0
            
            for i in f:
                counter+=1
                if c==1:                    
                    data=i.strip()
                    s.write(data)
                else:
                    data=i
                    s.write(data)
                                             
                if counter==c:
                    break

i get output of this 'Write a title that summarizes the specific problem\n\nThe title is the first thing potential answerers will see.\n\n' and i want it like this 'Write a title that summarizes the specific problem\n\nThe title is the first thing potential answerers will see. so what i should modify? i am picking up no of lines called c from a text file and writing it in another text file so i dont want the last line to add \n when i check it with ''' '''

ombk
  • 2,036
  • 1
  • 4
  • 16
  • Does this answer your question? [How can I remove a trailing newline?](https://stackoverflow.com/questions/275018/how-can-i-remove-a-trailing-newline) – Joe Ferndz Dec 05 '20 at 22:55

1 Answers1

0

if you want to remove "\n" from the end then you can simply use

with open("essay.txt",'r') as f:
    a_string=f.read()

c=3
a_string='\n'.join(a_string.splitlines()[:c]) #EDIT
a_string = a_string.rstrip("\n")  # rstrip helps to strip only from right

with open("out.txt",'w') as f:
    f.write(a_string)

OR

a_string='Write a title that summarizes the specific problem\n\nThe title is the first thing potential answerers will see.\n\n'
c=3
a_string='\n'.join(a_string.splitlines()[:c])
a_string=a_string.rstrip("\n")
print(a_string)

OUTPUT

>>> Write a title that summarizes the specific problem\n\nThe title is the first thing potential answerers will see.
Yash Makan
  • 706
  • 1
  • 5
  • 17