0

So for context I'm writing a program in python where I have an external file (user.txt) containing usernames and passwords. I want to create a list where each element is the username + password from each line in user.txt. So for example the first line in user.txt is 'jack, pass123', the list should read ['jackpass123'] and then say the second line in user.txt is 'dave, word543' then the list should read ['jackpass123', 'daveword543'].

Here is the code I've written:

f = open('user.txt', 'r+')
credentials = []
for line in f:
    line_split = line.split(', ')
    element = line_split[0] + line_split[1]
    credentials.append(element)
print(credentials)
f.close()

The list I get is: ['jackpass123\n', 'daveword543'] Note that '\n' is added to the end of each element except the last. Im guessing this is due to the format of the user.txt file but how can I get rid of it without changing the user.txt file.

Ultimately I want to be able to match a user input of username and password to match an element in this list but the '\n' is becoming a nuisance.

Thanks for any help

  • Try: `line.strip().split(', ')`. Also may I suggest opening the file using a context manager: `with open(...) as f:` Then you don't need to close the file, the context manager will handle that for you. – Cow Dec 27 '22 at 11:13
  • `element.replace("\n","")` before appending – Gameplay Dec 27 '22 at 11:13
  • or even `credentials.append(element.strip())` – bn_ln Dec 27 '22 at 11:14

1 Answers1

0
f = open('user.txt', 'r+')
credentials = []
for line in f:
    line_split = line.split(', ')
    element = (line_split[0] + line_split[1]).replace('\n', '')
    credentials.append(element)
print(credentials)
f.close()

You can use .replace to remove the \n

PW1990
  • 393
  • 1
  • 8