Python - Strip Text File Content

Introduction

The following code create a text file first.

Then it reads the content and strip the lines.

Demo

X, Y, Z = 43, 44, 45                       # Native Python objects 
S = 'Test'                                 # Must be strings to store in file 
D = {'a': 1, 'b': 2} 
L = [1, 2, 3] #   w  ww.  j  a  va2 s  .  c  om

F = open('datafile.txt', 'w')              # Create output text file 
F.write(S + '\n')                          # Terminate lines with \n 
F.write('%s,%s,%s\n' % (X, Y, Z))          # Convert numbers to strings 
F.write(str(L) + '$' + str(D) + '\n')      # Convert and separate with $ 
F.close() 

F = open('datafile.txt')# Open again 
line = F.readline()    # Read one line 
print( line )
print( line.rstrip() ) # Remove end-of-line

Result

Related Topic