使用for循环从Python的外部文件中打印列表的每个项目 [英] Using a for loop to print each item of a list from an external file in Python

查看:369
本文介绍了使用for循环从Python的外部文件中打印列表的每个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,该程序从.txt文件中读取2D列表,并且试图遍历该列表并打印其中的每个项目.我使用了for循环来遍历列表中的每个项目. .txt文件中的2D列表的内容为:

I am writing a program that reads a 2D list from a .txt file, and I'm trying to loop through the list, and print each item in it. I've used a for loop to loop through each item in the list. The contents of the 2D list in the .txt file is:

['1', '10']
['Hello', 'World']

到目前为止,这是我的代码,用于打开文件,读取文件并循环浏览列表中的每个项目:

This is my code so far for opening the file, reading it, and looping through each item in the list:

file = open('Original_List.txt', 'r')

file_contents = file.read()

for i in file_contents.split():
    print(i)           

file.close()

我从此for循环中获得的输出是:

The output that I get from this for loop is:

['1',
'10']
['Hello',
'World']

但是,我要获取的输出是:

However, the output that I'm trying to get is:

1       10
Hello   World

有什么办法可以获取此输出?我不确定如何删除方括号,逗号和引号.一旦完成,我就无法弄清楚如何设置行的格式,以使它们显示在外部文件中(每一项之间都有标签).我是Python的新手,所以任何建议都很棒!

Is there any way that I can get this output? I'm not sure how to remove the square brackets, commas and quotation marks. And once that is done, I can't figure out how to format the lines so that they are displayed as they appear in the external file (with the tabs between each item). I'm quite new to Python, so any suggestions would be great!

推荐答案

拆分换行符并以您的格式输出:

Splitting on newlines and outputting in your format:

from ast import literal_eval

file_contents = file.readlines() #read the file as lines
for line in file_contents:
    l = literal_eval(line) #convert the string to a list
    print(''.join([v.ljust(10, ' ') for v in l])) #left justify and print

这篇关于使用for循环从Python的外部文件中打印列表的每个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆