[英]Python reading \n on the end of a line
因此,我正在從文本文件中讀取內容以創建字典,但是一旦將\\ n添加到行的末尾...為什么呢?
蟒蛇
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)
文本文件
lamp, 000000, False
tv, 000000, False
bedside, 000000, False
pc, 000000, False
bed tv, 000000, False
您所有的行都有換行符; 您需要先刪除它,然后再處理該行:
value = line.rstrip('\n').split(",")
Python不會為您刪除它。 這里使用的str.rstrip()
方法將從行尾刪除任何數量的\\n
換行符; 永遠不會超過一個。 您也可以使用不帶參數的str.strip()
將其擴展到字符串兩端的任何空格。
您已經從字符串開始,因此這里不需要使用str()
調用。 如果您的行用逗號分隔,則可以使用csv
模塊並讓它處理行尾:
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
演示:
>>> 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')}
從行中刪除"\\n"
,然后再除以","
例如
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)
輸出:
{'tv': (0, 'False'), 'pc': (0, 'False'), 'lamp': (0, 'False'), 'bedside': (0, 'False'), 'bed tv': (0, 'False')}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.