Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You cannot add columns to an existing CSV file; you'll have to rewrite the whole file, I'm afraid.</p> <p>You can use the following context manager to make replacing a file a little easier:</p> <pre><code>from contextlib import contextmanager import io import os @contextmanager def inplace(filename, mode='r', buffering=-1, encoding=None, errors=None, newline=None, backup_extension=None): """Allow for a file to be replaced with new content. yields a tuple of (readable, writable) file objects, where writable replaces readable. If an exception occurs, the old file is restored, removing the written data. mode should *not* use 'w', 'a' or '+'; only read-only-modes are supported. """ # move existing file to backup, create new file with same permissions # borrowed extensively from the fileinput module if set(mode) &amp; set('wa+'): raise ValueError('Only read-only file modes can be used') backupfilename = filename + (backup_extension or os.extsep + 'bak') try: os.unlink(backupfilename) except os.error: pass os.rename(filename, backupfilename) readable = io.open(backupfilename, mode, buffering=buffering, encoding=encoding, errors=errors, newline=newline) try: perm = os.fstat(readable.fileno()).st_mode except OSError: writable = open(filename, 'w' + mode.replace('r', ''), buffering=buffering, encoding=encoding, errors=errors, newline=newline) else: os_mode = os.O_CREAT | os.O_WRONLY | os.O_TRUNC if hasattr(os, 'O_BINARY'): os_mode |= os.O_BINARY fd = os.open(filename, os_mode, perm) writable = io.open(fd, "w" + mode.replace('r', ''), buffering=buffering, encoding=encoding, errors=errors, newline=newline) try: if hasattr(os, 'chmod'): os.chmod(filename, perm) except OSError: pass try: yield readable, writable except Exception: # move backup back try: os.unlink(filename) except os.error: pass os.rename(backupfilename, filename) raise finally: readable.close() writable.close() try: os.unlink(backupfilename) except os.error: pass </code></pre> <p>Use this with the <code>csv</code> module to add columns:</p> <pre><code>with inplace(csvfilename, 'rb') as (infh, outfh): reader = csv.reader(infh) writer = csv.writer(outfh) for row in reader: row += ['new', 'column'] writer.writerow(row) </code></pre>
    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.
 

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