python中for循环打印列表,使用for循环从Python的外部文件中打印列表的每个项目

本文介绍了一个Python程序,该程序从.txt文件中读取2D列表,并尝试使用for循环遍历并打印列表的每个元素。目前的代码能读取文件但输出包含方括号、逗号和引号。目标是去除这些符号并使输出格式与原始文件一致,通过使用`ast.literal_eval()`解析字符串为列表,并使用`ljust`进行格式化打印。
摘要由CSDN通过智能技术生成

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

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

Is there any way that I can get this

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值