在Python中,调用例如temp = open(filename,'r').readlines()会得到一个列表,其中每个元素都是文件中的一行。然而,这些字符串在末尾有一个换行符,这是我不想要的。
我怎么能得到没有换行符的数据?
在Python中,调用例如temp = open(filename,'r').readlines()会得到一个列表,其中每个元素都是文件中的一行。然而,这些字符串在末尾有一个换行符,这是我不想要的。
我怎么能得到没有换行符的数据?
当前回答
试试这个:
u=open("url.txt","r")
url=u.read().replace('\n','')
print(url)
其他回答
temp = open(filename,'r').read().split('\n')
每次读取文件一行。使用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()
试试这个:
u=open("url.txt","r")
url=u.read().replace('\n','')
print(url)
temp = open(filename,'r').read().splitlines()