从附加CSV文件中删除最后一行

时间:2016-03-28 19:11:20

标签: python csv

我想删除附加到CSV文件的最后一行(有点像'撤消'最后添加的行)。到目前为止,我有一个接口,它接受用户生成的raw_input并执行命令。例如,'a'将行添加到CSV文件中,'r'拒绝CSV文件中的行。我想'你'删除添加到CSV文件的最后一行。我的代码看起来像这样

for i in range(0,len(out['bestObjID']),1):
    j = raw_input('\n Add (a) or Reject (r)?: ')
    if j=='ADD' or j=='add' or j=='a' or j=='A':
        c = csv.writer(open('NLS1_candidates.csv','a+'))
        c.writerow(out[i])
        print(' Writing object to candidate list...')
        i += 1
    elif j=='REJECT' or j=='reject' or j=='r' or j=='R':
        print(' Object rejected...')
        i += 1
    elif j=='UNDO' or j=='undo' or j=='u' or j=='U':
        i -= 1
    elif j=='?' or j=='h' or j=='help' or j=='HELP' or j=='H':
        print('    \n Press (a) to add object to candidate list')
        print('     Press (r) to add to reject object')
        print('     Press (?) or (h) for help')
        print('     Press (q) to Quit')
    elif j=='q' or j=='Q' or j=='QUIT' or j=='quit':
        print('\n Quitting...')
        break
    else:
        print('    \n Press (a) to add object to candidate list')
        print('     Press (r) to add to reject object')
        print('     Press (?) or (h) for help')
        print('     Press (q) to Quit')

如何将“撤消”功能添加到我的CSV文件中?

编辑:我没有提到当我向CSV文件添加行时,out[i]是从另一个CSV文件读取的行。如果这有帮助的话。

6 个答案:

答案 0 :(得分:1)

如果您的文件不大,可以按readlines()将它们存储在列表中并删除最后一行,然后使用相同的文件名写入该文件。

cat sample.csv                                                                                                                                                                    
line1
line2
line3
cat test.py                                                                                                                                                                       
inputs = open("sample.csv")
all_lines = inputs.readlines()
all_lines.pop(len(all_lines)-1)  # removes last line
inputs.close()  # closes file

# truncate file and write all lines except the last line
with open("sample.csv", "w") as out:
    for line in all_lines:
        out.write(line.strip() + "\n")

python test.py                                                                                                                                                                    
cat sample.csv                                                                                                                                                                    
line1
line2

答案 1 :(得分:0)

(脏)解决方案可以通过在开头指定EOF字符(可能是\n)来写入每一行, 并且,当应删除最后一行时,写下\r character

但是这不能处理多行删除。

答案 2 :(得分:0)

如果文件非常大,解决方案是定义NB_UNDO_LIMIT整数,该整数等于写入前在内存中保存的行数,允许用户最多撤消NB_UNDO_LIMIT倍增加。

from collections import deque

NB_UNDO_LIMIT = 10
output = open('output', 'w')

float_lines = deque(maxlen=NB_UNDO_LIMIT)
for line in open('filename'):
    # write the older line if necessary
    if len(float_lines) == NB_UNDO_LIMIT:
        output.write(float_lines.popLeft())
    float_lines.append(line)
    # do a job on the NB_UNDO_LIMIT last lines

答案 3 :(得分:0)

以下是未经测试的,但应该让您基本了解如何完成。 一个我询问您当前代码是否有效的原因是由于i循环内的for i in range(...):变量的手动操作。好像它可能会导致问题......

last_write = None

for i in range(0,len(out['bestObjID']),1):
    j = raw_input('\n Add (a) or Reject (r)?: ')
    if j=='ADD' or j=='add' or j=='a' or j=='A':
        with open('NLS1_candidates.csv', 'ab+') as f:
            f.seek(0, os.SEEK_END)
            last_write = f.tell()  # remember where added row starts
            c = csv.writer(f)
            print(' Writing object to candidate list...')
            c.writerow(out[i])
    elif j=='REJECT' or j=='reject' or j=='r' or j=='R':
        print(' Object rejected...')
        i += 1
    elif j=='UNDO' or j=='undo' or j=='u' or j=='U':
        if last_write is None:
            print(' Nothing to undo!')
        else:
            with open('NLS1_candidates.csv', 'ab+') as f:
                f.seek(last_write)  # go back to where last row started
                print(' Removing last row added.')
                f.truncate()  # reset file size back to that point
                last_write = None
                i -= 1
    elif j=='?' or j=='h' or j=='help' or j=='HELP' or j=='H':
        print('    \n Press (a) to add object to candidate list')
        print('     Press (r) to add to reject object')
        print('     Press (?) or (h) for help')
        print('     Press (q) to Quit')
    elif j=='q' or j=='Q' or j=='QUIT' or j=='quit':
        print('\n Quitting...')
        break
    else:
        print('    \n Press (a) to add object to candidate list')
        print('     Press (r) to add to reject object')
        print('     Press (?) or (h) for help')
        print('     Press (q) to Quit')

答案 4 :(得分:0)

*仅当您没有连续的UNDO时才会起作用。

如果对file.csv进行了一些更改,那么之前的副本将存储在file.csv~中 只需执行文件替换即可获取以前的内容。

答案 5 :(得分:0)

感谢wfgeo:另一个,我想一个简单的解决方法是使用os库,找到最后一行并截断它:

import csv
import os

with open(fileName, 'w', newline='') as f:
  writer = csv.writer(f, delimiter=';', dialect='excel')
  
  for row in rows:
    row = rows[0].values()
    writer.writerow(row)

  f.seek(0, os.SEEK_END)
  f.seek(f.tell()-2, os.SEEK_SET)
  f.truncate()