我一直在尝试打印我在第一行打开的整个txt。前3个方法不打印整个列表,最后一个方法确实如此,但我不知道如何格式化它以使其行中的每个元素分离。
myList = open("LIST.txt","r").readlines()
#print(*myList, sep='\n')
#for elem in myList:
# print (elem)
#print ('\n'.join(myList))
print(myList[0:])
答案 0 :(得分:0)
所有这些方法似乎都打印出所有行:
>>> my_list = open("list.txt").readlines()
>>> for elem in my_list:
... print (elem)
...
First line
Second line
Third line
>>> my_list = open("list.txt").readlines()
>>> for elem in my_list:
... print (elem)
...
First line
Second line
Third line
>>> print ('\n'.join(my_list))
First line
Second line
Third line
>>> print (''.join(my_list))
First line
Second line
Third line
>>> print(my_list[:])
['First line\n', 'Second line\n', 'Third line\n']
如果myList[0:]
有效,您可以使用加入:''.join(myList[0:])
。但是,如果您将线路重新组合在一起,则可能只需要read
而不是readlines
:
>>> print(open("list.txt").read())
First line
Second line
Third line