Home > Software design >  how can i sort file elements in python?
how can i sort file elements in python?

Time:05-07

I have to sort some elements in a text file that contains the names with the schedules of some teachers. Searching on google, I found this program:

def sorting(filename):
  infile = open(filename)
  words = []
  for line in infile:
    temp = line.split()
    for i in temp:
      words.append(i)
  infile.close()
  words.sort()
  outfile = open("result.txt", "w")
  for i in words:
    outfile.writelines(i)
    outfile.writelines(" ")
  outfile.close()
sorting("file.txt")

The code works, but it sorts the elements of the file on a single line, while I want it to be written as in the file, but in alphabetical and numerical orders. To unterstand it, let's say I have this file:

c
a
b

What I want is to sort it like this:

a
b
c

but it sorts it like this:

a b c

I use python 3.10. Can anyone please help me? Thanks.

CodePudding user response:


def sorting(filename):
  infile = open(filename)
  words = []
  for line in infile:
    temp = line.split()
    for i in temp:
      words.append(i)
  infile.close()
  words.sort()
  outfile = open("result.txt", "w")
  for i in words:
    outfile.writelines(i)
    outfile.writelines("\n") # edited Instead of ' ' write '\n'
  outfile.close()
sorting("test.txt")

CodePudding user response:

def sorting(filename):
  infile = open(filename)
  words = []
  for line in infile:
    temp = line.split()
    for i in temp:
      words.append(i)
  infile.close()
  words.sort()
  outfile = open("result.txt", "w")
  for i in words:
    outfile.writelines(i)
    outfile.writelines("\n")
  outfile.close()
sorting("file.txt")

to sort them with a new line use "\n" instead of " "

  • Related