- 在进行 Python 编程时,遇到一个问题:在使用 replace_line 函数替换文件中的一行时,会在新行后添加一个空格。
- 想要只在替换后的新行后添加一个空格,而不是在每一行后都添加空格。
-
解决方案:
- 问题的原因是 replace_line 函数在替换行时,使用了 out.writelines('\n'.join(lines)) 来写入文件,这会导致在每一行后都添加一个换行符。
- 为了解决这个问题,需要在 text 变量中包含一个换行符 '\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 块结束后被正确关闭,即使在发生异常时也是如此。
代码示例:
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
with open(file_name, 'r') as fin, open(file_name, 'w') as out:
lines = fin.readlines()
lines[line_num] = text + '\n'
out.writelines(lines)
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("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("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("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("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("Names.txt", num, phrase_change)
names.close
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
希望这篇技术文章对您有所帮助!