Reputation: 1087
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
Upvotes: 0
Views: 1171
Reputation: 10213
Remove "\n"
from line before split by ","
e.g.
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')}
Upvotes: 1
Reputation: 1121306
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')}
Upvotes: 1