如何在替换文件中的行时添加空格

时间:2013-11-30 21:00:30

标签: python

我正在完成一项任务。我对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 个答案:

答案 0 :(得分: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关键字   对象。这样做的好处是文件在之后正确关闭   它的套件即使在路上引发异常也会完成。