我有一个文本文件sample.txt
,其中包含以下数据:
Name of Person: John
Age: 24 years
Height: 170 cm
Weight: 64 kg
我的代码是:
list_for_dictionary = []
filename='sample.txt'
f = open(filename)
for line_number, line in enumerate(f, 1):
key="data_values"
dictionary = {key: {"fileLine": line, "lineNumber": int(line_number), "fileName": filename}}
list_for_dictionary.append(dictionary)
print(list_for_dictionary)
我得到的输出是:
[{'data_values': {'fileLine': 'Name of Person: John\n', 'lineNumber': 1, 'fileName': 'sample.txt'}}, {'data_values': {'fileLine': 'Age: 24 years\n', 'lineNumber': 2, 'fileName': 'sample.txt'}}, {'data_values': {'fileLine': 'Height: 170 cm\n', 'lineNumber': 3, 'fileName': 'sample.txt'}}, {'data_values': {'fileLine': 'Weight: 24kgs', 'lineNumber': 4, 'fileName': 'sample.txt'}}]
我的问题是,为什么'\n'
被添加到fileLine
的每一行的末尾,我该如何摆脱呢?”
答案 0 :(得分:1)
将line.strip()
用于{'fileLine': line.strip()}