0

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?'

blhsing
  • 91,368
  • 6
  • 71
  • 106
Slickmind
  • 442
  • 1
  • 7
  • 15
  • 1
    Use line.strip(), \n is a new line. Your file records contains line be line values. That's why you are getting a \n. – Mohamed Thasin ah Oct 02 '18 at 03:17
  • They come out of `for line in f`, or out of `f.readlines()`, that way; it's not "being added" anywhere else, but is *always* part of using an iterator-based interface to read a text file in Python. – Charles Duffy Oct 02 '18 at 03:18

1 Answers1

1

Use line.strip() for your {'fileLine': line.strip()}

vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20