Home > Mobile >  Python, print with double quotes per line
Python, print with double quotes per line

Time:10-15

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 that print format instead of printing lines directly because I want the double quotation marks per item per line.

CodePudding user response:

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() '",')

CodePudding user response:

When you are iterating over file, it's like file1.readlines(), which adds '\n' at the end of the line. Try this code:

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

CodePudding user response:

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()

CodePudding user response:

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

CodePudding user response:

Have you checked the format inside the text file? there might already be some invisible \n (return character) that you just can't see, and it stacks with your print which also adds a \n at the end of the line.

CodePudding user response:

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()   '",')
  • Related