I am working on a simple import routine that translates a text file to a json file format for our system in python.
import json
# Open text file for reading
txtFile = open('Boating.Make.txt', 'r')
# Create picklist obj
picklistObj = dict()
picklistObj['name'] = 'Boating.Make'
picklistObj['items'] = list()
i = 0
# Iterate through each make in text file
for line in txtFile:
picklistItemObj = dict()
picklistItemObj['value'] = str(i)
picklistItemObj['text'] = line.strip()
picklistItemObj['selectable'] = True
picklistObj['items'].append(picklistItemObj)
i = i + 1
txtFile.close()
picklistJson = json.dumps(picklistObj, indent=4)
print picklistJson
picklistFile = open('Boating.Make.json', 'w')
picklistFile.write(picklistJson)
picklistFile.close()
My question is, why do I need the “strip”? I thought that python was supposed to magically know the newline constant for whatever environment I am currently in. Am I missing something?
I should clarify that the text file I am reading from is an ASCII file that contains lines of text separated ‘\r\n’.
Python keeps the new line characters while enumerating lines. For example, when enumerating a text file such as
you get two strings:
"foo\n"and"bar\n". If you don’t want the terminal new line characters, you callstrip().I am not a fan of this behavior by the way.