【问题标题】:Find and delete after 1st occurance of empty row in csv with python [closed]使用python在csv中第一次出现空行后查找和删除[关闭]
【发布时间】:2013-10-08 04:42:14
【问题描述】:

我想删除第一次出现空行后的所有行。

  1. 向下阅读行直到遇到空行的最佳方法是什么?
  2. 删除所有后续行的最佳命令是什么?

【问题讨论】:

  • 通过输入代码。 (你试过什么?到目前为止你的代码在哪里?)
  • 如果你不给我们任何代码可以使用,我们怎么给你任何使用?
  • 有几种方法可以做到这一点,如果文件不是太大,我建议将所有数据读入一个变量,关闭文件,然后逐行写入相同的文件名虽然该行不为空,但弓大是您需要处理的文件吗?

标签: python csv


【解决方案1】:

这是一个您可以使用的脚本。 main 函数中的代码只是为了允许您选择一个文件(或者如果给定,则将其作为命令行参数选择)。然后调用crop_file函数,该函数通过打开文件、将数据读取到内存中的第一个空行、关闭文件然后将存储的数据写入同一个文件(如果您确认需要)来执行您在问题中描述的操作其余行已删除。

如果您对代码有任何疑问,请告诉我。

#!/usr/bin/python

import os, csv, sys, Tkinter, tkFileDialog as fd

# stop tinker shell from opening as only needed for file dialog
root = Tkinter.Tk()
root.withdraw()

def crop_file(in_path):
    # read file into memory
    file_obj = open(in_path, 'rb')
    reader = csv.reader(file_obj, delimiter='\t')
    data = []
    for row in reader:
        if not row or not any(row):
            break #stop at empty row
        else:
            data.append(row)
    file_obj.close()

    print 'Found', len(data), 'rows of data without empty lines.'
    conf = raw_input('delete remaining lines? (Y|N): ').upper()[0]

    if conf == 'Y':
        # write data to file
        file_obj = open(in_path, 'wb')
        writer = csv.writer(file_obj)
        writer.writerows(data)
        file_obj.close

def main():
    in_path = None
    prog_name = sys.argv[0]

    # check if in_path are inlcuded as cmd line args...
    if len(sys.argv) > 1:
        in_path = sys.argv[1]
        if not os.path.exists(in_path):
            print 'Usage:', prog_name, '[file_path>]'
            print 'cannot find the file provided for file_path:\n', in_path
            sys.exit("Error - invalid excel_file_path arg")
    else:
        try:
            # set current working directory to user's my documents folder
            os.chdir(os.path.join(os.getenv('userprofile'),'documents'))
        except:
            pass

    # ask user for path to file...
    while not in_path:
        print "Please select the file to read data from ..."
        try:
            in_path = fd.askopenfilename()
        except:
            print 'Error selecting file.'
        if not in_path:
            cont = raw_input('Do you want to continue? (Y|N): ').upper()[0]
            if cont == 'N':
                sys.exit("Error - unable to select input file")

    crop_file(in_path)

if __name__ == '__main__':
    main()

【讨论】:

  • 这段代码识别出我有 33 行条目,但在我的 .csv 中实际上有 26 行,然后是 3 个空白行,最后是 5 行数据(这些是要已删除。)我该如何更改它以使其仅选择前 26 行并删除其余行?
  • @gigawatts 这就是它对我检查它的测试数据所做的事情。您能否将您的数据发布在诸如 hastebin 之类的地方并向我发送链接,然后我将针对您的数据进行尝试并进行必要的修改(显然,如果有任何个人详细信息等,您应该先将数据匿名)。
  • @gigawatts 我怀疑这是我的测试文件和你的测试文件之间的空行中的细微差别。您的空白行是字面上是空的还是包含空格等?
  • 非常感谢您的帮助,因为我对 Python 非常陌生。我在对原始帖子的编辑中对您的原始代码进行了细微调整...
  • @gigawatts 很高兴你最终到达了那里。我已经用您所做的更改更新了上面的帖子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-10
  • 2022-11-22
  • 1970-01-01
相关资源
最近更新 更多