Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding quotes and commas to lines in a file

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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="")
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading