954,515 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

How to write a string from an array to a file alphabetically?

I want to build a script that does the following:
The script should do make an arry from the directory where the script is with os.listdir(). Then the script has to test if the value in the array already excists in the outcome file, if not the name in the array should be written to the file alphabetically.

For example:

array=['test123','hallo','ABC','zipcode','myname','computer','test456']

The outcome in my file should be:
ABC
computer
hallo
myname
test123
test456
zipcode

Could anyone please help me to make a script like this?
I already started making this: But the problem with this is. That everything is written to 'films.txt' and nothing is checked if the name in lijst_films already excists in 'films.txt'

import os,sys,re

lijst_films=os.listdir()
file='films.txt'

if not os.path.exists(file):
    file=open('films.txt','w')
    file.close()

for x in lijst_films:
    print(x)
    x=re.sub('20\d\d*.*', '', x)
    x=re.sub('1080*.*', '', x)
    x=re.sub('\(' ,'' ,x)
    x=re.sub('\)' ,'' ,x)
    x=x.replace('.'or'',' ')
    x=x.replace('[isoHunt]','')
    if x[-1] == ' ':
        x=x.replace(x,x[:-1])
    if x[-0] == ' ':
        x=x.replace(x,x[1:])
    print(x)
    with open('films.txt','a') as file:
        file.write('%s\n' %(x))


Thank you in advance.

jantrancero
Newbie Poster
7 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
 

This might help ...

array = ['test123','hallo','ABC','zipcode','Myname','computer','test456']

# sort case insensitive
sorted_array = sorted(array, key=str.lower)

print(array)
print(sorted_array)

''' result -->
['test123', 'hallo', 'ABC', 'zipcode', 'Myname', 'computer', 'test456']
['ABC', 'computer', 'hallo', 'Myname', 'test123', 'test456', 'zipcode']
'''
vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

I am going to test this out!

Thanks for the reply!

jantrancero
Newbie Poster
7 posts since Dec 2011
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You
View similar articles that have also been tagged: