【问题标题】:Displaying and formatting list from external file in Python在 Python 中显示和格式化来自外部文件的列表
【发布时间】:2018-04-19 00:35:04
【问题描述】:

我有一个外部文件,我正在从中读取列表,然后打印出列表。到目前为止,我有一个 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']

我已经完成了,我已经设法将列表中的项目分成单独的行,但我仍然需要删除方括号、引号和逗号。我尝试使用循环遍历该行中的每个项目,并且仅在它不包含任何方括号、引号和逗号时才显示它,但是当我这样做时,它会将列表项分隔为单个字符,而不是将其保留为一个完整的项目。我还需要能够显示第一个项目,然后将其覆盖,然后打印第二个项目等,以便输出看起来与外部文件相同,除了方括号、引号和逗号被删除。关于如何做到这一点的任何建议?我是 Python 新手,非常感谢任何帮助!

【问题讨论】:

标签: python-3.x list for-loop


【解决方案1】:

格式化是你的朋友。

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 2012-12-01
    • 1970-01-01
    • 2017-07-03
    • 2012-02-29
    • 1970-01-01
    相关资源
    最近更新 更多