2013-11-30 2 views
2

Я работаю над заданием. Я очень новичок в Python и в программировании в целом.Как добавить пустое место при замене строки в файле

Мое назначение - создать меню со списком имен друзей. Затем я должен иметь возможность печатать имена, добавлять имя, изменять имя и стирать имя. Я работаю над изменением имени. Моя проблема в том, что когда я меняю имя, он добавляет новое пространство после каждого имени. Я просто хочу добавить пробел после нового имени. Я думаю, что проблема заключается в определении replace_line.

Вот мой код:

from tkinter import*    #imports the Tkinter (GUI) library 
master = Tk()     # Creates a Tk root widget to initialize Tkinter 


names_list = Listbox(master)     # Creates the listbox 
names_list.pack() 

names_list.insert(0,"Print List of Names") 
names_list.insert(1,"Add Name")  #This populates the listbox with the different options 
names_list.insert(2,"Change Name") 
names_list.insert(3,"Remove Name") 
names_list.insert(4,"Quit") 

def replace_line(file_name, line_num, text):   # This creates the function that will erase names 
lines = open(file_name, 'r').readlines() 
lines[line_num] = text 
out = open(file_name, 'w') 
out.writelines('\n'.join(lines))   # Problem Here, adding a new line to every element 
out.close() 

def CurSelect(evt):     # defines the CurSelect function that will print out the the value latter selected in the listbox 
value=str((names_list.get(names_list.curselection()))) 

if value =="Print List of Names":   # What to do if "Print List of Names" is selected 
    names = open("C:/Users/Jonathan/Desktop/Classes/GPC/Intro to Comp Sci/Python Name Book Assignment/Names.txt",'r') 
    for name in names:   #reads names as a list line by line istead of all on one line 
    print(name) 
    names.close 
else: 
    if value == "Add Name":   # What to do if "Add Name" is selected 
    names = open("C:/Users/Jonathan/Desktop/Classes/GPC/Intro to Comp Sci/Python Name Book Assignment/Names.txt",'a') 
    new_name=input("Type the name you would like to add and press enter")   # This creates a variable that is passes to file.write for appending 
    names.write(new_name) 
    names.write("\n")     # This adds a new line after appending the new_name variable 
    names.close 
    else: 
     if value == "Change Name":   # What to do if "Change Name" is selected 
      names = open("C:/Users/Jonathan/Desktop/Classes/GPC/Intro to Comp Sci/Python Name Book Assignment/Names.txt",'r') 
      phrase = input("Enter name to change")   # Looks for the name to change 
      for line in names:   # Looks for the line number that the name to change is on 
       if phrase in line: 
        with open("C:/Users/Jonathan/Desktop/Classes/GPC/Intro to Comp Sci/Python Name Book Assignment/Names.txt",'r') as myFile: 
        for num, line in enumerate(myFile, 0): 
         if phrase in line:    # Actually replaces the name with a new name entered by the user 
         phrase_change = input("Enter name to change to") 
         replace_line("C:/Users/Jonathan/Desktop/Classes/GPC/Intro to Comp Sci/Python Name Book Assignment/Names.txt", num, phrase_change) 


names_list.bind('<<ListboxSelect>>',CurSelect)  #binds the selection in the listbox to the Curselect function 


master.mainloop()       # Tkinter Event Loop: make the window actually appear 

ответ

1

Линии возвращаемой file.readlines уже содержат косую '\n', так что вам просто нужно добавить '\n' к тексту вы заменяющий:

def replace_line(file_name, line_num, text): 
    with open(file_name, 'r') as fin, open(file_name, 'w') as out: 
     lines = fin.readlines() 
     lines[line_num] = text + '\n'    #This should contain a '\n' 
     out.writelines(lines) 

Всегда используйте инструкцию with для обработки файла, он будет убедиться, что файл закрыт, как только выйдет блок with, даже если возникает исключение.

От docs:

Это хорошая практика, чтобы использовать with ключевое слово при работе с файлом объектов. Это имеет то преимущество, что файл правильно закрыт после завершения , даже если в пути возникло исключение.

Смежные вопросы