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