Reading strings from a text file in python (windows)

I am working on a simple import procedure that converts a text file to json 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 a "strip"? I thought python should have magically learned the newline constant for any environment that I currently live in. Did I miss something?

I must clarify that the text file I am reading is an ASCII file containing lines of text separated by "\ r \ n".

+3
source share
4 answers

Python saves new string characters when listing strings. For example, when listing a text file such as

foo
bar

you will get two lines: "foo\n"and "bar\n". If you do not need new terminal string characters, you call strip().

By the way, I'm not a fan of this behavior.

+3
source

. this.

Python ; "U" , : Unix '\n', Macintosh '\ r', Windows '\ r\n'

+1

(), " :" . ( , 2.71, ). , file.readline(), , .

0

Python :

open('test1.txt', 'wb').write(b'Hello\nWorld!')
open('test2.txt', 'wb').write(b'Hello\r\nWorld!')
print(list(open('test1.txt'))) # Shows ['Hello\n', 'World!']
print(list(open('test2.txt'))) # Shows ['Hello\n', 'World!']

Python . strip myString.replace('\n', ''). :

>>> help(str.strip)
Help on method_descriptor:

strip(...)
    S.strip([chars]) -> str

    Return a copy of the string S with leading and trailing
    whitespace removed.
    If chars is given and not None, remove characters in chars instead.

>>> help(str.replace)
Help on method_descriptor:

replace(...)
    S.replace(old, new[, count]) -> str

    Return a copy of S with all occurrences of substring
    old replaced by new.  If the optional argument count is
    given, only the first count occurrences are replaced.
0

All Articles