1

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.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
EeveeLover
  • 89
  • 1
  • 5
  • Use the `end` argument of `print`: https://docs.python.org/3/library/functions.html#print – Random Davis Oct 14 '22 at 17:26
  • 1
    @RandomDavis No, this is not the problem here. – Matthias Oct 14 '22 at 17:34
  • Does this answer your question? [Read file and remove \n and spaces from lines](https://stackoverflow.com/questions/68272031/read-file-and-remove-n-and-spaces-from-lines) – Gino Mempin Oct 15 '22 at 02:57
  • The title and the question is misleading, as it's not about printing and not about the double-quotes, but about stripping the newline character when reading lines from a file, which is addressed by [Read file and remove \n and spaces from lines](https://stackoverflow.com/questions/68272031/read-file-and-remove-n-and-spaces-from-lines) or the more canonical duplicate [How to read a file without newlines](https://stackoverflow.com/q/12330522/2745495) – Gino Mempin Oct 15 '22 at 03:01

5 Answers5

2

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

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()
Ben Grossmann
  • 4,387
  • 1
  • 12
  • 16
1

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() + '",')
Mohammad
  • 11
  • 3
0

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', '')+'",')
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
szachy-a
  • 21
  • 5
0
file = open('notes.txt', 'r')
lines = file.read().split('\n')
for line in lines:
    print(f'"{line}",')
islam abdelmoumen
  • 662
  • 1
  • 3
  • 9