繁体   English   中英

在python 2.7中-如何从csv读取数据,重新格式化数据并写入新的csv

[英]In python 2.7 - How to read data from csv, reformat data, and write to new csv

我是一个正在编程的菜鸟,我被困住了...我的目标是打开一个csv文件(从程序A导出),重新格式化数据,并将其写入新的csv文件中(以供程序B导入) 。 我知道我的代码不是很漂亮,尽管它可以工作到写入新的csv文件。 它仅写入旧csv中的最后一行数据。

import csv

print 'Enter file location or press enter for default location.'
aPath = raw_input('> ')  # user path to file
if aPath == '':
    aPath = '/default/path/to/file'  # default path
aFile = raw_input('Enter file name: ')  # user file name
if aFile == '':
    aFile = 'orginal.csv'  # default file name
myCSV = csv.DictReader(open(aPath + aFile, 'r'), delimiter=',')
print myCSV.fieldnames # verify fieldnames

for p in myCSV:
    w = csv.writer(open("output.csv", "w"))
    try:
        p = dict((k, v) for k, v in p.iteritems()
            if v.lower() != 'null')
    except AttributeError, e:
        print e
        print p
        raise Exception()
# reformats the columns of data for the output.csv
    pID = p.get('Last Name')[-4:]
    pName = p.get('Last Name')[:-4].strip() + ', ' + p.get('First Name')
    pDate = p.get('Start Time')[:-5]
    pBlank = p.get('')
    pCourse = p.get('Assigned Through')
    pScore = p.get('Score')[:-1]

# verifies the new columns
    print pID, pName, pDate, pBlank, pCourse, pBlank, pBlank, pScore

# NOT working...Only writes the last row of the orginal.csv to output.csv
    w.writerow([pID, pName, pDate, pBlank, pCourse, pBlank, pBlank, pScore])

您将重新打开文件,并for p in myCSV循环中的for p in myCSV每次传递时将其覆盖。 进入for循环之前,您需要创建一次w

以下修改后的代码应该可以工作:

import csv

print 'Enter file location or press enter for default location.'
aPath = raw_input('> ')  # user path to file
if aPath == '':
    aPath = '/default/path/to/file'  # default path
aFile = raw_input('Enter file name: ')  # user file name
if aFile == '':
    aFile = 'orginal.csv'  # default file name
myCSV = csv.DictReader(open(aPath + aFile, 'r'), delimiter=',')
print myCSV.fieldnames # verify fieldnames

with open("output.csv", "wb") as ofile:
    w = csv.writer(ofile)
    for p in myCSV:
        try:
            p = dict((k, v) for k, v in p.iteritems()
                if v.lower() != 'null')
        except AttributeError, e:
            print e
            print p
            raise Exception()
    # reformats the columns of data for the output.csv
        pID = p.get('Last Name')[-4:]
        pName = p.get('Last Name')[:-4].strip() + ', ' + p.get('First Name')
        pDate = p.get('Start Time')[:-5]
        pBlank = p.get('')
        pCourse = p.get('Assigned Through')
        pScore = p.get('Score')[:-1]

    # verifies the new columns
        print pID, pName, pDate, pBlank, pCourse, pBlank, pBlank, pScore

    # NOT working...Only writes the last row of the orginal.csv to output.csv
        w.writerow([pID, pName, pDate, pBlank, pCourse, pBlank, pBlank, pScore])

我们改变的事情:

  1. 我们使用了with运算符。 当使用打开和关闭文件进行操作时,遵循with是一种普遍接受的协议,除非另外不适用,因为它可以正确处理文件的关闭等操作。
  2. 使用wb而不是仅将w作为open的第二个参数。 这将允许您以写二进制模式打开文件。 请参阅作为参考。

希望这可以帮助。

恐怕您会在每次迭代时重新编写输出文件...您应该简单地选择这一行

w = csv.writer(open("output.csv", "w"))

跳出循环为:

w = csv.writer(open("output.csv", "w"))
try:
    for p in myCSV:
        try:
            ...
            w.writerow([pID, pName, pDate, pBlank, pCourse, pBlank, pBlank, pScore])
finally:
    w.close()

您还可以查看“带有”结构,该结构可自动处理潜在的io错误,并在块末尾关闭文件,而无需进行其他尝试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM