Displaying and formatting list from external file in Python - python-3.x

I have an external file that I'm reading a list from, and then printing out the list. So far I have a for loop that is able to read through the list and print out each item in the list, in the same format as it is stored in the external file. My list in the file is:
['1', '10']
['Hello', 'World']
My program so far is:
file = open('Original_List.txt', 'r')
file_contents = file.read()
for i in file_contents.split():
print(i)
file.close()
The output I'm trying to get:
1 10
Hello World
And my current output is:
['1',
'10']
['Hello',
'World']
I'm part way there, I've managed to separate the items in the list into separate lines, but I still need to remove the square brackets, quotation marks, and commas. I've tried using a loop to loop through each item in the line, and only display it if it doesn't contain any square brackets, quotation marks, and commas, but when I do that, it separates the list item into individual characters, rather than leave it as one entire item. I also need to be able to display the first item, then tab it over, and print the second item, etc, so that the output looks identical to the external file, except with the square brackets, quotation marks, and commas removed. Any suggestions for how to do this? I'm new to Python, so any help would be greatly appreciated!

Formatting is your friend.
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()

Related

Problem with reading text then put the text to the list and sort them in the proper way

Open the file romeo.txt and read it line by line. For each line, split the line into a list of words using the split() method. The program should build a list of words. For each word on each line check to see if the word is already in the list and if not append it to the list. When the program completes, sort and print the resulting words in alphabetical order.
This is the question my problem is I cannot write a proper code and gathering true data, always my code gives me 4 different lists for each raw!
** This is my code**
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line=line.rstrip()
line =line.split()
if line in last:
print(true)
else:
lst.append(line)
print(lst)
*** the text is here, please copy and paste in text editor***
But soft what light through yonder window breaks
It is the east and Juliet is the sun
Arise fair sun and kill the envious moon
Who is already sick and pale with grief
You are not checking the presence of individual words in the list, but rather the presence of the entire list of words in that line.
With some modifications, you can achieve what you are trying to do this way:
fname = input("Enter file name: ")
fh = open(fname)
lst = list()
for line in fh:
line = line.rstrip()
words = line.split()
for word in words:
if word not in lst:
lst.append(word)
print(lst)
However, a few things I would like to point out looking at your code:
Why are you using rstrip() instead of strip()?
It is better to use list = [] as opposed to your lst = list(). It is shorter, faster, more Pythonic and avoids the use of this confusing lst variable.
You should want to remove punctuation marks attached to words, eg: ,.: which do not get removed by split()
If you want a loop body to not do anything, use pass. Why are you printing true? Also, in Python, it's True and not true.

remove white spaces from the list

I am reading from a CSV file and appending the rows into a list. There are some white spaces that are causing issues in my script. I need to remove those white spaces from the list which I have managed to remove. However can someone please advise if this is the right way to do it?
ip_list = []
with open('name.csv') as open_file:
read_file = csv.DictReader(open_file)
for read_rows in read_file:
ip_list.append(read_rows['column1'])
ip_list = list(filter(None, ip_list))
print(ip_list)
Or a function would be preferable?
Here is a good way to read a csv file and store in list.
L=[] #Create an empty list for the main array
for line in open('log.csv'): #Open the file and read all the lines
x=line.rstrip() #Strip the \n from each line
L.append(x.split(',')) #Split each line into a list and add it to the
#Multidimensional array
print(L)
For example this csv file would produce an output like
This is the first line, Line1
This is the second line, Line2
This is the third line, Line3
This,
List = [('This is the first line', 'Line1'),
('This is the second line', 'Line2'),
('This is the third line', 'Line3')]
Because csv means comma seprated values you can filter based on commas

white space added in the beginning of new line when printing in new line

When I try to print whatever data on several lines using python 3, a single whitespace gets added to the beginning of all the lines except first one. for example:
[in] print('a','\n','b','\n','c')
the output will be:
a
b
c
but my desired output is:
a
b
c
so far I've only been able to do this by doing three print commands. Anyone has any thoughts?
From the docs:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Print objects to the text stream file, separated by sep and followed by end.
sep, end, file and flush, if present, must be given as keyword
arguments.
Calling print('a', '\n', 'b') will print each of those three items with a space in between, which is what you are seeing.
You can change the separator argument to get what you want:
print('a', 'b', sep='\n')
Also see the format method.

Using a for loop to print each item of a list from an external file in Python

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

I have a single line list and want to covert it to a multi dimensional list

I have a text file that I converted into a list, but I want it to be a multi-dimensional list. Is there a way to do this easily?
This is my code:
crimefile = open(fileName, 'r')
yourResult = [line.split(',') for line in crimefile.readlines()]
Your code does create a 2-dimensional list (assuming your file is multiple lines of numbers where each number is separated by a comma). If you want to print out each individual list in yourResult, try this: for list in yourResult: print (list) To access a certain item in the list, for example the first number on each line, simply replace print (list) with print (list[0])

Resources