2013-10-01 27 views
-4

我想在第一次出現空行後刪除所有行。在python中第一次出現空行csv後查找並刪除

  1. 什麼是最好的方式來讀取行直到遇到一個空行?
  2. 什麼是刪除所有正在進行的行的最佳命令?
+4

通過輸入代碼。 (你有什麼試過的?你的代碼到目前爲止在哪裏?) – Doorknob

+1

如果你不給我們任何代碼來使用,我們如何給你使用? – iCodez

+0

有幾種方法可以做到這一點,如果文件不是太大,我建議將所有數據讀入一個變量,關閉文件,然後逐行寫入相同的文件名,而行不是空的,然後弓大是你需要處理的文件? – ChrisProsser

回答

0

這是您可以使用的腳本。主函數中的代碼只是爲了讓您選擇一個文件(或者如果給出,可以將其作爲命令行參數選取)。然後調用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() 
+0

這段代碼認識到我有33行有條目,但在我的.csv中實際上有26行,然後是3空白行,然後是5行數據(這些是要刪除的行)。這樣它才能選擇前26行並刪除其餘行? – gigawatts

+0

@ gigawatts這就是它爲我所檢查的測試數據所做的。你可以將你的數據發佈到像hastebin這樣的地方,然後給我一個鏈接,然後我會根據你的數據嘗試它,並做出修改(顯然如果有任何個人信息等,你應該首先匿名數據)。 – ChrisProsser

+0

@ gigawatts我懷疑這與我的測試文件和你的測試文件之間的空行差別很大。你的空白行字面上是空的還是包含空格等? – ChrisProsser

相關問題