D
D
Dazai2021-07-11 16:08:01
Python
Dazai, 2021-07-11 16:08:01

How to sort a file alphabetically?

I have a file with this content:

"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH","JENNIFER","MARIA","SUSAN","MARGARET","DOROTHY","LISA","NANCY","KAREN","BETTY","HELEN","SANDRA","DONNA","CAROL","RUTH","SHARON","MICHELLE","LAURA","SARAH","KIMBERLY","DEBORAH","JESSICA","SHIRLEY","CYNTHIA","ANGELA","MELISSA","BRENDA","AMY","ANNA","REBECCA","VIRGINIA","KATHLEEN","PAMELA","MARTHA","DEBRA","AMANDA","STEPHANIE","CAROLYN","CHRISTINE","MARIE","JANET","CATHERINE","FRANCES","ANN","JOYCE","DIANE","ALICE","JULIE","HEATHER","TERESA","DORIS","GLORIA","EVELYN","JEAN","CHERYL","MILDRED","KATHERINE","JOAN","ASHLEY","JUDITH","ROSE","JANICE","KELLY","NICOLE","JUDY","CHRISTINA","KATHY","THERESA","BEVERLY","DENISE","TAMMY","IRENE","JANE","LORI","RACHEL","MARILYN","ANDREA","KATHRYN","LOUISE","SARA","ANNE","JACQUELINE","WANDA","BONNIE","JULIA","RUBY","LOIS","TINA","PHYLLIS","NORMA","PAULA","DIANA","ANNIE","LILLIAN","EMILY","ROBIN","PEGGY","CRYSTAL","GLADYS","RITA","DAWN","CONNIE","FLORENCE","TRACY","EDNA","TIFFANY","CARMEN","ROSA","CINDY","GRACE","WENDY","VICTORIA","EDITH","KIM","SHERRY","SYLVIA","JOSEPHINE","THELMA","SHANNON","SHEILA","ETHEL","ELLEN","ELAINE","MARJORIE","CARRIE","CHARLOTTE","MONICA","ESTHER","PAULINE","EMMA","JUANITA","ANITA","RHONDA","HAZEL","AMBER","EVA","DEBBIE","APRIL","LESLIE","CLARA","LUCILLE","JAMIE","JOANNE","ELEANOR","VALERIE","DANIELLE","MEGAN","ALICIA","SUZANNE","MICHELE","GAIL","BERTHA","DARLENE","VERONICA","JILL","ERIN","GERALDINE","LAUREN","CATHY","JOANN","LORRAINE","LYNN","SALLY","REGINA","ERICA","BEATRICE",

I need to sort all the names alphabetically I
tried many ways from the Internet, the last one looked like this:
file = open('p022_names.txt','r')
names = file.readlines()
b = sorted(names)
print(b)

But it displays only the contents of the file in the list, how to sort alphabetically?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vindicar, 2021-07-11
@DazaiCoder

I tried many ways from the Internet, you say ...
Then you need to turn on your head and think for yourself. The first step is to break the task down into subtasks.
Task #1: read the contents of the input file.
Task #2: Turn the read line into a list of elements to be sorted
Task #3: Sort the list according to the desired criteria
Task #4: Write the sorted list to an output file.
Now for the points.
No. 1. You're wrong about .readlines() creating a list where each line is one element. You have all the elements of the list on the same line, so readlines() won't help you. Using just .read()

with open('p022_names.txt', 'rt', encoding='utf-8') as src: #а может кодировка не utf-8? Тогда поменяй на нужную
    content = src.read() #читаем всё содержимое файла в память. Если файл размером под гигабайт, будет весело... но для маленьких файлов сойдёт
# with позволяет гарантированно автоматически закрыть файл по выходу из блока

No. 2. Google work with strings in python. The biggest question is: can there be a comma in the name? If not, then everything is solved very simply: This will give us a list of strings, but with three caveats. 1) the last comma will give us the list element - an empty string. If this is not allowed, then you should get rid of empty lines:
items = content.split(',')
items = [item for item in content.split(',') if item != '']

2) Strings in lists will be in quotes. This will not affect sorting, but if you need to get rid of them, you will need one more step.
3) If there is a newline \n at the end of the line, then you need to get rid of it before splitting: content = content.rstrip()
No. 3. Sort the list in place: items.sort(). Unlike the .sort() method, sorted() creates and returns a new sorted list without touching the old one. Descending if needed, items.sort(reverse=True).
No. 4. to glue the elements back. If the last comma is needed, then . .join() is more efficient than going through the for loop manually. Well, write to a file:content = ','.join(items)content = (','.join(items)) + ','
with open('p022_names_sorted.txt', 'wt', encoding='utf-8') as dst: # можно писать и в тот же самый файл - он уже закрыт к этому моменту, так что можем его переоткрыть для записи.
    dst.write(content)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question