Answer the question
In order to leave comments, you need to log in
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",
file = open('p022_names.txt','r')
names = file.readlines()
b = sorted(names)
print(b)
Answer the question
In order to leave comments, you need to log in
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 позволяет гарантированно автоматически закрыть файл по выходу из блока
items = content.split(',')
items = [item for item in content.split(',') if item != '']
content = content.rstrip()
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 questionAsk a Question
731 491 924 answers to any question