在Python中,调用例如temp = open(filename,'r').readlines()会得到一个列表,其中每个元素都是文件中的一行。然而,这些字符串在末尾有一个换行符,这是我不想要的。
我怎么能得到没有换行符的数据?
在Python中,调用例如temp = open(filename,'r').readlines()会得到一个列表,其中每个元素都是文件中的一行。然而,这些字符串在末尾有一个换行符,这是我不想要的。
我怎么能得到没有换行符的数据?
当前回答
每次读取文件一行。使用str.rstrip(chars)从字符串末尾删除不需要的字符。
with open(filename, 'r') as fileobj:
for row in fileobj:
print(row.rstrip('\n'))
请参见str.strip([chars])和str.lstrip([chars])。
其他回答
my_file = open("first_file.txt", "r")
for line in my_file.readlines():
if line[-1:] == "\n":
print(line[:-1])
else:
print(line)
my_file.close()
每次读取文件一行。使用str.rstrip(chars)从字符串末尾删除不需要的字符。
with open(filename, 'r') as fileobj:
for row in fileobj:
print(row.rstrip('\n'))
请参见str.strip([chars])和str.lstrip([chars])。
您可以使用列表推导式轻松地将文件读取为列表
with open("foo.txt", 'r') as f:
lst = [row.rstrip('\n') for row in f]
试试这个:
u=open("url.txt","r")
url=u.read().replace('\n','')
print(url)
我最喜欢的一行程序——如果你不从pathlib import Path:)
lines = Path(filename).read_text().splitlines()
这将自动关闭文件,不需要使用open()…
在Python 3.5中添加。
https://docs.python.org/3/library/pathlib.html#pathlib.Path.read_text