Home > OS >  Adding quotes and commas to lines in a file
Adding quotes and commas to lines in a file

Time:04-12

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:

  1. Each line contains a trailing newline when you first read it in. Use:

    line.rstrip()
    

    rather than line in the format string.

  2. Unrelated to the issue you're asking about, but worth pointing out: you should close the file handle using fhand.close() after the for 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="")
    
  • Related