Writeline 不写入第 3 行和第 4 行

Writeline doesn't write to 3rd and 4th lines

奇怪的是,即使这些是相同的代码,第 3 行和第 4 行写在 txt 文件的第 5 行上。

代码如下:

def save():
    with open("save.txt", "w") as f:
        f.writelines([filename1, "\n"+filename2, "\n"+filename3, "\n"+filename4, "\n"+filename5+"\n"])

当所有的文件名都是“a”时

输出为:

a
a


a

只有filename3是“a”时

输出为:





a

我用这个代码取文件名

filename3 = filedialog.askopenfilename()

这里是相关代码

filename1 = ""
filename2 = ""
filename3 = ""
filename4 = ""
filename5 = ""

def uploadFile3(fname):
    global filename3
    filename3 = filedialog.askopenfilename()
    fname.config(text=filename3)

def save():
    with open("save.txt", "w") as f:
        f.writelines([filename1, "\n"+filename2, "\n"+filename3, "\n"+filename4, "\n"+filename5+"\n"])

buttonc = tk.Button(window, text="Add File", command= lambda: uploadFile3(program3)).pack()
program3 = Label(window, text=filename3)
program3.pack()

buttonaa = Button(window, text="Save", command=save)

这些现在是硬编码的,有 5 个名为 uploadFile1、uploadFile2 等的函数。

感谢您的回答

filename1 = "a"
filename2 = "b"
filename3 = "c"
filename4 = "d"
filename5 = "e"



def save():
    with open("save.txt", "w") as f:
        f.writelines([filename1, "\n"+filename2, "\n"+filename3, "\n"+filename4, "\n"+filename5+"\n"])

我得到以下输出。


a
b
c
d
e

您的保存功能正常

这是一个基于您的代码片段的备选方案:

def save(lines):
    with open('save.txt', 'w') as f:
        f.writelines('\n'.join(lines))

然后您可以简单地将 save() 调用为:

save([filename1, filename2, filename3, filename4, filename5])

只要您觉得需要对变量进行编号,就不要这样做。使用列表,例如:

filename = ["","","","",""]

作为 filename[0] - filename[4].

访问

然后用换行符连接所有字符串。使用 print 重定向到文件也将为最后一行提供最终的换行符:

filename=['a','b','c','','d']
with open('save.txt','w') as f:
    print('\n'.join(filename),file=f)