我有一个外部文件,我正在从中读取一个列表,然后打印出该列表。到目前为止,我有一个for循环,它能够读取列表并以与存储在外部文件中相同的格式打印出列表中的每一项。我在文件中的列表是:
['1', '10']
['Hello', 'World']到目前为止我的程序是:
file = open('Original_List.txt', 'r')
file_contents = file.read()
for i in file_contents.split():
print(i)
file.close()我尝试获取的输出如下:
1 10
Hello World我现在的输出是:
['1',
'10']
['Hello',
'World']我已经做到了一部分,我已经设法将列表中的项目分隔成单独的行,但我仍然需要删除方括号、引号和逗号。我曾尝试使用循环遍历行中的每一项,并仅在它不包含任何方括号、引号和逗号时才显示它,但当我这样做时,它会将列表项分隔为单独的字符,而不是将其作为一个完整的项。我还需要能够显示第一个项目,然后按tab键并打印第二个项目,等等,以便输出看起来与外部文件相同,只是去掉了方括号、引号和逗号。对如何做到这一点有什么建议吗?我是Python的新手,所以如果有任何帮助,我将不胜感激!
发布于 2018-04-19 08:45:23
格式化是你的朋友。
file = open('Original_List.txt', 'r'))
file_contents = file.readlines() # change this to readlines so that it splits on each line already
for list in file_contents:
for item in eval(list): # be careful when using eval but it suits your use case, basically turns the list on each line into an 'actual' list
print("{:<10}".format(i)) # print each item with 10 spaces of padding and left align
print("\r\n") # print a newline after each line that we have interpreted
file.close()https://stackoverflow.com/questions/49910936
复制相似问题