I am trying to read some strings from a file that looks like this:
123456
password
12345678
qwerty
123456789
12345
1234
111111
1234567
dragon
...till the end
I want to print each line to a file with quotes and commas inserted in the following way,
"123456",
"password",
"12345678",
...till the end
I tried:
fhand = open("pass.txt")
for line in fhand:
print(f'"{line}",',end="")
But, this code prints quotes and commas in the wrong place:
"123456
","password
","12345678
","qwerty
...till the end
How can I remove these spurious newlines?
CodePudding user response:
Two things:
Each line contains a trailing newline when you first read it in. Use:
line.rstrip()
rather than
line
in the format string.Unrelated to the issue you're asking about, but worth pointing out: you should close the file handle using
fhand.close()
after thefor
loop. Even better, use a context manager instead, which will automatically close the file handle for you:with open("pass.txt") as fhand: for line in fhand: print(f'"{line.rstrip()}",',end="")