EeveeLover
EeveeLover

Reputation: 89

How to print lines from a file wrapped in double quotes?

I'm trying to print lines from a text file to look like this format:

"line one",
"line two",
"line three",

I'm using this code

file1 = open('notes.txt', 'r')
lines = file1.readlines()
for line in lines:
    print('"'+line+'",')

but it ends up looking like this instead:

"line one
",
"line two
",
"line three",

Is there a way so that it isn't just the last line that has its closing quotation mark on the same line? I'm using print to format instead of printing the lines directly because I want the double quotation marks per item per line.

Upvotes: 1

Views: 454

Answers (5)

szachy-a
szachy-a

Reputation: 21

When you are iterating over file with file1.readlines(), it adds '\n' at the end of the line.

Try this code:

lines = file1.readlines()
for line in lines:
    print('"'+line.replace('\n', '')+'",')

Upvotes: 0

Mohammad
Mohammad

Reputation: 11

Use the rstrip()

The rstrip method returns a new string with trailing whitespace removed, whitespace includes the hidden '\n' at the very end of each line, which indicates the end of the line. Therefore, here is the solution.

    file1 = open('notes.txt', 'r')
    lines = file1.readlines()
    for line in lines:
        print('"' + line.rstrip() + '",')

Upvotes: 1

Brandon Han
Brandon Han

Reputation: 21

The reason you're getting this is because the file you're reading from contains \n at the end of each line. Use rstrip() to remove it.

file1 = open('notes.txt', 'r')
lines = file1.readlines()
for line in lines:
    print('"'+line.rstrip()+'",')

Upvotes: 2

islam abdelmoumen
islam abdelmoumen

Reputation: 664

file = open('notes.txt', 'r')
lines = file.read().split('\n')
for line in lines:
    print(f'"{line}",')

Upvotes: 0

Ben Grossmann
Ben Grossmann

Reputation: 4782

The readlines command doesn't remove the newline character at the end of each line. One approach is to instead do

file1 = open('notes.txt', 'r')
lines = file1.read().splitlines()

Upvotes: 1

Related Questions