将过滤后的CSV文件写入新文件并迭代文件夹

时间:2013-11-11 17:31:35

标签: python csv

我一直在尝试创建一个程序来浏览一个文件并选择某些列然后将其移动到新的文本文件中。到目前为止我已经

    import os, sys, csv
    os.chdir("C://Users//nelsonj//Desktop//Master_Project")
    with open('CHS_2009_test.txt', "rb") as sitefile:
    reader = csv.reader(sitefile, delimiter=',')
    pref_cols = [0,1,2,4,6,8,10,12,14,18,20,22,24,26,30,34,36,40]

    for row in reader:
        new_cols = list(row[i] for i in pref_cols)
        print new_cols

我一直在尝试使用csv函数来编写新文件,但我不断收到错误。我最终需要在一个文件夹上执行此操作,但我想在解决这个问题之前我会先尝试一下。

我尝试使用代码将此数据写入新文件

    for row in reader:
        with open("CHS_2009_edit.txt", 'w') as file:
            new_cols = list(row[i] for i in pref_cols)
            newfile = csv.writer(file)
            newfile.writerows(new_cols)

这种方法的工作原理是我获得了一个新文件,但只打印了来自我的csv的第二行值,即不是标题值,并在每个单独的字符之间放置逗号,而不仅仅是复制原始列就像他们一样。

我在Python 2.6(来自ArcGIS)中使用PythonWin

感谢您的帮助!

新更新的代码

   import os, sys, csv

   path = ('C://Users//nelsonj//Desktop//Master_Project')

   for filename in os.listdir(path):

       pref_cols = [0,1,2,4,6,8,10,12,14,18,20,22,24,26,30,34,36,40]
       with open(filename, "rb") as sitefile:
           with open(filename.rsplit('.',1)[0] + "_Master.txt", 'w') as output_file:
               reader = csv.reader(sitefile, delimiter=',')
               writer = csv.writer(output_file)
               for row in reader:
                   new_row = list(row[i] for i in pref_cols)
                   writer.writerow(new_row)
                   print new_row

获取new_row的列表索引超出范围,但似乎仍在处理该文件。我现在唯一无法做到的就是遍历我目录中的所有文件。这是指向Screenshot of data text file

的超链接

2 个答案:

答案 0 :(得分:1)

试试这个:

 new_header = list(row[i] for i in pref_cols if i in row)

这应该避免错误,但它可能无法避免潜在的问题。你会将CSV文件粘贴到我可以访问的地方,我会为你解决这个问题吗?

答案 1 :(得分:0)

出于过滤目的,您不必以不同于其他数据的方式处理标题。您可以继续删除以下块:

    headers = reader.next()
    for row in headers:
        new_header = list(row[i] for i in pref_cols)
        print new_header  

您的代码无效,因为您将标题视为行列表,但标题只是一行。

更新

此更新涉及将CSV数据写入新文件。您应该将open语句移到for row...

之上
with open("CHS_2009_edit.txt", 'w') as output_file:
    writer = csv.writer(output_file)
    for row in reader:
        new_cols = list(row[i] for i in pref_cols)
        writer.writerows(new_cols)

更新2

此更新处理标头输出问题。如果你按照我的建议,你应该没有这个问题。我不知道您当前的代码是什么样的,但看起来您提供了代码需要列表的字符串。这是我在我的系统上尝试的代码(使用我的虚拟数据),它似乎有效:

pref_cols = [...] # <<=== Should be set before entering the loop
with open('CHS_2009_test.txt', "rb") as sitefile:
    with open('CHS_2009_edit.txt', 'w') as output_file:
        reader = csv.reader(sitefile, delimiter=',')
        writer = csv.writer(output_file)
        for row in reader:
            new_row = list(row[i] for i in pref_cols)
            writer.writerow(new_row)

有一点需要注意:我使用writerow()来编写一行,您使用writerows() - 这会产生影响。