954,541 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to get rid of newline char

Hi,

Below is my test code, i have a list of names in a file, i read the names and i have to insert them as menu options in the menubar. Since its a dynamic menu and people can add new menu's it has to be read from a file everytime its loaded. Problem is that its appending an extra character after everyname in the menu, something line '[]'(check the attached screen shot) which i assume is the newline char, since i'm inserting that too... How can i get rid of that, any suggestions? i tried reading and writing the file in binary mode but makes no difference.

from Tkinter import *

fileObj = open("c:/test","w")
fileObj.write("rajat")
fileObj.write("\n")
fileObj.write("prasun")
fileObj.close()

file1 = open("c:/test","r")
lines = file1.readlines()
file1.close()

root = Tk()
menubar = Menu(root)
filemenu = Menu(menubar)
menubar.add_cascade(label="Names",menu=filemenu)

for line in lines:
    filemenu.add_cascade(label=line)

root.config(menu=menubar)
root.mainloop()
Attachments tk.bmp (39.48KB)
Agni
Practically a Master Poster
655 posts since Dec 2007
Reputation Points: 431
Solved Threads: 116
 

Use string method strip() to remove newline characters.

for line in lines:
    filemenu.add_cascade(label=line.strip())
solsteel
Junior Poster
145 posts since Mar 2007
Reputation Points: 86
Solved Threads: 42
 

simple and exact ... worked perfectly... Thanks a lot.

Agni
Practically a Master Poster
655 posts since Dec 2007
Reputation Points: 431
Solved Threads: 116
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You