Split Text File Content
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] # from www .j av a2s .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() # Next line from file print( line ) # It's a string here parts = line.split(',') # Split (parse) on commas print( parts ) print( line ) # It's a string here parts = line.split(',') # Split (parse) on commas print( parts )
We used the string split method here to chop up the line on its comma delimiters.
F = open('datafile.txt') # Open again line = F.readline() # Next line from file print( line ) # It's a string here parts = line.split(',') # Split (parse) on commas # w w w . jav a2 s .c om #print( int(parts[1]) ) # Convert from string to int #numbers = [int(P) for P in parts] # Convert all in list at once #print( numbers )