向文本文件添加行

2024-03-28 15:08:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在txt文件的末尾添加一行。我在这里读了一些文章,尝试了不同的选项,但是,由于某种原因,新行没有添加在最后一行之后,它只是附加在最后一行之后。你知道吗

所以我想知道我做错了什么…这里我展示了我的测试:

测试1:

#newProt is a new data entered by the user in this case 12345
exists = False
f = open('protocols.txt', 'a+')
for line in f:
    if newProt == line:
        exists = True

if not exists:
    f.write(newProt)
f.close()

此代码后的txt文件:

2sde45

21145

we34z12345

测试2:

exists = False
with open('protocols.txt', 'r+') as f:
    for line in f:
        if newProt == line:
            exists = True

    if not exists:
        f.write(newProt)

此代码后的txt文件:与上面完全相同。。。你知道吗

像这样,我测试了一些字母组合来打开文件,rb+,w,等等,但是由于某些原因,我从来没有得到想要的输出txt文件:

^{2}$

所以我不知道我做错了什么,我下面是一些例子,我从其他一些职位在这里戈尔。你知道吗


Tags: 文件代码intxtfalsetrueforif
2条回答

试试这个:

exists = False
f = open('protocols.txt', 'a+')
for line in f:
    if newProt == line:
        exists = True

if not exists:
    f.write('\n' + newProt)
f.close()

这将在文件末尾添加新行字符,然后添加“newProt”。你知道吗

编辑:

代码没有产生所需结果的原因是,您只是在向文件中写入一个字符串。文本中的新行不是真正的“在”文本文件中。文本文件实际上是一系列字节,称为chars。各种应用程序(如文本编辑器)显示新行的原因是,它将某些字符解释为格式元素,而不是字母或数字。你知道吗

“\n”就是这样一个格式化字符(在ASCII标准中),它告诉您喜爱的文本编辑器开始新行。还有其他的,比如'\t',它是一个制表符。你知道吗

有关详细信息,请查看the wiki article on Newline character

可以使用f.seek(-x,x),到达最后一行,然后使用f.write()。你知道吗

否则,我的理解是,如果你以“a”(append)模式打开一个文件,它最终还是会被写入的

请参阅以下链接:Appending line to a existing file having extra new line in Python

相关问题 更多 >