简体   繁体   中英

Python reading \n on the end of a line

So I'm reading from a text file to make a dictionary, however once it's adding \\n on to the end of the line... Why is this?

Python

irTable = {}
with open("devices.txt") as file:
        for line in file:
                value = line.split(",")
                label = str(value[0])
                freq = int(value[1])
                state = str(value[2])

                irTable[label] = freq, state
                print(irTable)

Text file

lamp, 000000, False
tv, 000000, False
bedside, 000000, False
pc, 000000, False
bed tv, 000000, False

All your lines have the newline; you need to remove it first before processing the line:

value = line.rstrip('\n').split(",")

Python doesn't remove it for you. The str.rstrip() method used here will remove any number of \\n newline characters from the end of the line; there will never be more than one. You could also extend this to any whitespace, on both ends of the string, by using str.strip() with no arguments.

You already start with strings, so there is no need to use str() calls here. If your lines are comma-separated, you could just use the csv module and have it take care of line endings:

import csv

irTable = {}
with open("devices.txt", newline='') as file:
    for label, freq, state in csv.reader(file, skipinitialspace=True):
        irTable[label] = int(freq), state

Demo:

>>> from io import StringIO
>>> import csv
>>> demofile = StringIO('''\
... lamp, 000000, False
... tv, 000000, False
... bedside, 000000, False
... pc, 000000, False
... bed tv, 000000, False
... ''')
>>> irTable = {}
>>> for label, freq, state in csv.reader(demofile, skipinitialspace=True):
...     irTable[label] = int(freq), state
... 
>>> irTable
{'lamp': (0, 'False'), 'tv': (0, 'False'), 'bedside': (0, 'False'), 'bed tv': (0, 'False'), 'pc': (0, 'False')}

Remove "\\n" from line before split by "," eg

irTable = {}
with open("111.txt") as file:
    for line in file:
        value = line.strip().split(",")
        irTable[value[0].strip()] = int(value[1]), value[2].strip()
print(irTable)

Output:

{'tv': (0, 'False'), 'pc': (0, 'False'), 'lamp': (0, 'False'), 'bedside': (0, 'False'), 'bed tv': (0, 'False')}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM