StuartDTO
StuartDTO

Reputation: 1041

Write a file ascii ordened

I'm trying to copy one file to another one ascii ordened, but is giving me some bugs, for example on the first line it adds a \n with no reason, I'm trying to understand it but I don't get it, also if you think this way is not a good one please advice to me to do it better, thanks.

demo.txt (An ascii file)

!=orIh^
-_hIdH2 !=orIh^
-_hIdH2

code .py

count = 0
try:
    fcopy = open("demo.txt", 'r')
    fdestination = open("demo2.txt", 'w')
    for line in fcopy.readlines():
        count = len(line) -1
        list1 = ''.join(sorted(line))
        str1 = ''.join(str(e) for e in list1)
        fdestination.write(str(count)+str1)
    fcopy.close()
    fdestination.close()
except Exception, e:
    print(str(e))

Note count is the count of letters that are on a line

Output

7
!=I^hor15
!-2=HII^_dhhor6-2HI_dh

the problem is it should be the number of letters and then ordened asciily

Upvotes: 0

Views: 39

Answers (1)

DYZ
DYZ

Reputation: 57075

Each line in your code has a newline character at the end. When you sort all characters, the newline character is sorted, too, and moved to the appropriate position (which is in general not at the end of the string anymore). This causes line breaks to happen at almost random places.

What you need is to remove the line break before sorting and add it back after sorting. Also, the second join in your loop is not doing anything, and list1 is not a list but a string.

str1 = ''.join(sorted(line.strip('\n')))    
fdestination.write(str(count)+str1+'\n')

Upvotes: 3

Related Questions