I have a text file sample.txt
containing data as:
Name of Person: John
Age: 24 years
Height: 170 cm
Weight: 64 kg
My code is:
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)
The output which I am getting is :
[{'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'}}]
My question is why '\n'
is getting added at the end of each line in fileLine
and how can I get rid of it?'
Use line.strip()
for your {'fileLine': line.strip()}