Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Wednesday, March 26, 2008

Remove leading and trailing whitespace

To remove leading and trailing whitespace(or any trailing char):

  • Regular Expression :
    • s/^\s+//;
    • s/\s+$//;
  • Perl :
    • Chomp();
  • Python:
    • strip();

Monday, March 24, 2008

How to read and write text file in python

list1=file("filename.txt").readlines() #don't forget the parenthesis
set1=set(liste1) #cast it to a set

set1=[elem.strip() for elem in set1] #strip all the elements of the set by removing trailing characters such us /t or /n

To find the differences with another set :
set3=set1.difference(set2)

To save into a file
fLog=tFile.open('filename.log','w')

First I add line return to each elem of the set
set4=[elem+"\n" for elem in set3]

Then I write the whole set into the file:

fLog.writelines(set4)
fLog.close()