Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在替换文件中的行时添加空格_Python - Fatal编程技术网

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

Python 如何在替换文件中的行时添加空格,python,Python,我正在做一项任务。一般来说,我对Python和编程非常陌生 我的任务是创建一个包含朋友姓名列表的菜单。然后我应该能够打印姓名、添加姓名、更改姓名和删除姓名。我正在修改一个名字。我的问题是,当我更改一个名称时,它会在每个名称后添加一个新的空格。我只想在新名称后添加一个空格。我认为问题在于替换线的定义 这是我的密码: from tkinter import* #imports the Tkinter (GUI) library master = Tk()

我正在做一项任务。一般来说,我对Python和编程非常陌生

我的任务是创建一个包含朋友姓名列表的菜单。然后我应该能够打印姓名、添加姓名、更改姓名和删除姓名。我正在修改一个名字。我的问题是,当我更改一个名称时,它会在每个名称后添加一个新的空格。我只想在新名称后添加一个空格。我认为问题在于替换线的定义

这是我的密码:

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
从tkinter导入*#导入tkinter(GUI)库
master=Tk()#创建一个Tk根小部件来初始化Tkinter
名称_list=Listbox(主)#创建Listbox
名称\u list.pack()
姓名列表。插入(0,“打印姓名列表”)
名称列表。插入(1,“添加名称”)#这将使用不同的选项填充列表框
姓名列表。插入(2,“更改姓名”)
姓名列表。插入(3,“删除姓名”)
姓名列表。插入(4,“退出”)
def replace_line(文件名、行数、文本):#这将创建一个擦除名称的函数
lines=open(文件名为'r')。readlines()
行[行数]=文本
out=open(文件名“w”)
out.writelines('\n'.join(lines))#这里的问题是,为每个元素添加新行
结束
def CurSelect(evt):#定义CurSelect函数,该函数将打印列表框中选择的值
value=str((names\u list.get(names\u list.curselection()))
如果值==“打印姓名列表”:#如果选择了“打印姓名列表”,该怎么办
names=open(“C:/Users/Jonathan/Desktop/Classes/GPC/Comp-Sci/Python-Name-Book-Assignment/names.txt”“r')
对于名称中的名称:#将名称作为列表逐行读取,并在一行中读取所有名称
印刷品(名称)
名字,结束
其他:
如果值==“添加名称”:#如果选择了“添加名称”,该怎么办
names=open(“C:/Users/Jonathan/Desktop/Classes/GPC/Comp-Sci/Python-Name-Book-Assignment/names.txt”“a”“)
new_name=input(“键入要添加的名称并按enter键”)#这将创建一个传递到file.write以进行追加的变量
名字。写(新名字)
name.write(“\n”)35;这会在附加新的_name变量后添加一行
名字,结束
其他:
如果值==“更改名称”:#如果选择了“更改名称”,该怎么办
names=open(“C:/Users/Jonathan/Desktop/Classes/GPC/Comp-Sci/Python-Name-Book-Assignment/names.txt”“r')
短语=输入(“输入要更改的名称”)#查找要更改的名称
对于名称中的行:#查找要更改的名称所在的行号
如果一行中有短语:
以open(“C:/Users/Jonathan/Desktop/Classes/GPC/Intro to Comp Sci/Python Name Book Assignment/Names.txt,'r')作为我的文件:
对于num,枚举(myFile,0)中的行:
如果第行中的短语:#实际使用用户输入的新名称替换名称
短语_change=输入(“输入要更改的名称”)
替换_行(“C:/Users/Jonathan/Desktop/Classes/GPC/Intro to Comp Sci/Python Name Book Assignment/Names.txt”,num,短语_change)
name_list.bind(“”,CurSelect)#将列表框中的选择绑定到CurSelect函数
master.mainloop()#Tkinter事件循环:使窗口实际出现

文件返回的行。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
块退出,即使发生异常,文件也会立即关闭

发件人:

处理文件时,最好将
关键字一起使用 物体。这样做的好处是,文件在关闭后会正确关闭 它的套件完成了,即使在途中出现了异常