栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

写入CSV时将列添加到CSV

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

写入CSV时将列添加到CSV

您不能将列添加到现有的CSV文件中;恐怕您将不得不重写整个文件。

您可以使用以下上下文管理器来简化文件的替换:

from contextlib import contextmanagerimport ioimport os@contextmanagerdef 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) & 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

将此与

csv
模块一起使用以添加列:

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)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/652201.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号