从.txt文件中读取字符串' \ n'在字符串后自动放置。我可以删除吗?

时间:2017-01-10 06:57:02

标签: python

当我得到我的最终输出时,字符串会添加\n到最后。有没有办法可以删除它,还是只是readlines()函数的一部分?程序本身接受用户输入的字符串,将它们保存到文件中,然后读取文件以显示输入的字符串。一切正常,我似乎无法摆脱最终答案中添加的额外字符。

def readstring(f, line):
    string = line.strip('\r\n')
    return string

def writestring(f, string):
    f.write('\n' + string)

num_lines1 = sum(1 for line in open('string.txt'))

with open("string.txt", "a+", encoding="utf-8") as f:
    cont = "Y"
    while cont.upper() == "Y":
        d = input("Enter input or, enter q to exit loop:")
        g = 0
        if d != "q":
            string = d
            writestring(f, string)
            h = g + 1
        else:
            print("saving.....")
            break

    f.seek(0)

    for line in f:
        print(readstring(f,line))

num_lines2 = sum(1 for line in open('string.txt'))

r = num_lines2 - num_lines1
print(r)

f.close()

with open("string.txt", "r",) as f:
    lines = f.readlines()[num_lines1:num_lines2]
    print(lines)

f.close()

2 个答案:

答案 0 :(得分:1)

在字符串上使用rstrip()方法删除换行符。

lines = [l.rstrip('\n') for l in f.readlines()[num_lines1:num_lines2]]

答案 1 :(得分:0)

您可以在逐行阅读时删除结束换行符,或者调用rstrip删除"行"中每个项目的结束换行符。列表。

lines = map(lambda x: x.rstrip(), f.readlines()[num_lines1:num_lines2])

尾随换行符保留在字符串

def readline(self, length=None):
    r"""
    A trailing newline character is kept in the string (but may be absent
    when a file ends with an incomplete line). ...
    """
    ...
    i = self.buf.find('\n', self.pos)
    ...

def readlines(self, sizehint = 0):
    ...
    line = self.readline()
    ...