user13916921
user13916921

Reputation:

beginner issue with python : how to make one list of separated lines in a file in python

I have an issue as a beginner that made me exhausted trying to solve it so many times/ways but still feel dump, the problem is that I have a small file that I read in python and I have to make a list of the whole lines to sort it in alphabetical order. but when I try to make it in a list, it makes a separate list for each line.

here is my may that I tried to solve the issue using it:

file = open("romeo.txt")
for line in file:
    words = line.split()
    unique = list()
    if words not in unique:
        unique.extend(words)
        unique.sort()
        print(unique)

output:

['But', 'breaks', 'light', 'soft', 'through', 'what', 'window', 'yonder']
['It', 'Juliet', 'and', 'east', 'is', 'is', 'sun', 'the', 'the']
['Arise', 'and', 'envious', 'fair', 'kill', 'moon', 'sun', 'the']
['Who', 'already', 'and', 'grief', 'is', 'pale', 'sick', 'with']

Upvotes: 1

Views: 53

Answers (2)

Aleksander Ikleiw
Aleksander Ikleiw

Reputation: 2685

To have a list of all lines you can use simple

with open(your_file, 'r') as f:
    data = [''.join(x.split('\n')) for x in f.readlines()] # I used simple list comprehension to delete the `\n` at the end.

In data you have each line in a list. To sort the list you have to use sorted()

new_list = sorted(data)

now the new_list is the sorted list.

Upvotes: 1

Uday Kiran
Uday Kiran

Reputation: 229

You have a inbuilt function for it

lines_of_files = open("filename.txt").readlines()

This returns a list of each line in the file.Hope this solves you question

Upvotes: 0

Related Questions