-1

So i've wrtitten this code:

CaseList = []
f_Case = open("C:/Users/Luke Roberts/Desktop/Lists/CaseList.txt", "r")
for line in f_Case:
    CaseList.append(line)
print(CaseList)

but when i print the list it comes out as:

['Case 1\n', 'Case 2\n', 'Case 3\n', 'Case 4\n', 'Case 5']

Is there a way to have it be added to the list without the '\n'? If not, is there a way to remove the '\n' from each string?

Any and all help is appreciated! Cheers

cs95
  • 379,657
  • 97
  • 704
  • 746

1 Answers1

5

By default, lines are always read in from the file along with the trailing newline. Just call str.rstrip and get rid of it.

for line in f_Case:
    CaseList.append(line.rstrip())

Now, CaseList should look something like:

['Case 1', 'Case 2', 'Case 3', 'Case 4', 'Case 5']

Statutory Advice: You should wrap file I/O within a with...as context manager, it's makes for much cleaner code.

with open("C:/Users/Luke Roberts/Desktop/Lists/CaseList.txt", "r") as f_Case:
    for line in f_Case:
        CaseList.append(line)

This way, you won't have to call f_Case.close() (which you don't currently do, but should've), so you've got the added convenience to go with the safety.

cs95
  • 379,657
  • 97
  • 704
  • 746
  • Keep in mind that `line.rstrip()` will remove more than just newlines. You may want to use `line.rstrip('\r\n')` instead. – Aran-Fey Aug 28 '17 at 00:43