Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can read the whole file and split lines using <a href="https://docs.python.org/2/library/stdtypes.html#str.splitlines" rel="noreferrer"><code>str.splitlines</code></a>:</p> <pre><code>temp = file.read().splitlines() </code></pre> <p>Or you can strip the newline by hand:</p> <pre><code>temp = [line[:-1] for line in file] </code></pre> <p><strong>Note:</strong> this last solution only works if the file ends with a newline, otherwise the last line will lose a character.</p> <p>This assumption is true in most cases (especially for files created by text editors, which often <em>do</em> add an ending newline anyway).</p> <p>If you want to avoid this you can add a newline at the end of file:</p> <pre><code>with open(the_file, 'r+') as f: f.seek(-1, 2) # go at the end of the file if f.read(1) != '\n': # add missing newline if not already present f.write('\n') f.flush() f.seek(0) lines = [line[:-1] for line in f] </code></pre> <p>Or a simpler alternative is to <code>strip</code> the newline instead:</p> <pre><code>[line.rstrip('\n') for line in file] </code></pre> <p>Or even, although pretty unreadable:</p> <pre><code>[line[:-(line[-1] == '\n') or len(line)+1] for line in file] </code></pre> <p>Which exploits the fact that the return value of <code>or</code> isn't a boolean, but the object that was evaluated true or false.</p> <hr> <p>The <code>readlines</code> method is actually equivalent to:</p> <pre><code>def readlines(self): lines = [] for line in iter(self.readline, ''): lines.append(line) return lines # or equivalently def readlines(self): lines = [] while True: line = self.readline() if not line: break lines.append(line) return lines </code></pre> <p>Since <code>readline()</code> keeps the newline also <code>readlines()</code> keeps it.</p> <p><strong>Note:</strong> for symmetry to <code>readlines()</code> the <a href="https://docs.python.org/3/library/io.html#io.IOBase.writelines" rel="noreferrer"><code>writelines()</code></a> method does <em>not</em> add ending newlines, so <code>f2.writelines(f.readlines())</code> produces an exact copy of <code>f</code> in <code>f2</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload