如何在没有换行符“/n”的情况下从 .txt 文件追加一行

How to append a line from .txt file without new line character "/n"

我必须读取 txt 文件,例如:

test
test2
test3
test4

如果我使用这个代码

read_of_string = open("mylink.txt", "r")
read_of_string = read_of_string.readlines()
print(read_of_string)

一个输出是["test/n","test2/n","test3/n","test4/n"]

如果我使用此代码

print(read_of_string[0])

输出为“测试”(输入)

我必须将它附加到

listofstring = []
listofsting.append(read_of_string)

它不工作 输出应该是一个没有输入的字符串列表,比如

["test","test2","test3","test4"]

这是如何工作的?

a = ["test\n","test2\n","test3\n","test4\n"]
b = [item.rstrip() for item in a]
print(b)
['test', 'test2', 'test3', 'test4']

只需使用str.splitlines()方法:

read_of_string = read_of_string.read().splitlines()

所以在你的代码中,它应该是:

read_of_string = open("mylink.txt", "r")
read_of_string = read_of_string.read().splitlines()
print(read_of_string)

但请注意,使用 with 处理程序打开文件是更好的做法:

with open("mylink.txt", "r") as r:
    read_of_string = r.read().splitlines()
    print(read_of_string)