如果上面有[' \ x1a']标记,则删除最后一行

时间:2017-09-11 14:26:20

标签: python csv

我目前正在开发一个项目,我需要测试输入的最后一行(行)是否有这个字节:'\x1a'。如果最后一行有这个标记,我想删除整行。

到目前为止我有这段代码,但我不知道如何让它在最后一行测试该字节并将其删除。

谢谢!

readFile1 = open("sdn.csv")
lines1 = readFile1.readlines()
readFile1.close()
w1 = open("sdn.csv", 'w')
w1.writelines([item for item in lines1[:-1]])
w1.close()

readFile2 = open("add.csv")
lines2 = readFile2.readlines()
readFile2.close()
w2 = open("add.csv",'w')
w2.writelines([item for item in lines2[:-1]])
w2.close()

readFile3 = open("alt.csv")
lines3 = readFile3.readlines()
readFile3.close()
w = open("alt.csv",'w')
w.writelines([item for item in lines3[:-1]])
w.close()

1 个答案:

答案 0 :(得分:2)

在任何代码块中,您已将文件的内容读入变量,其中包含以下行:

lines1 = readFile1.readlines()

如果您想查看文本最后一行中\x1a字节是否存在 ,那么您可以这样做:

if '\x1a' in lines1[-1]:
    # whatever you need to do

如果要查找该字节,然后实际上从列表中删除该行:

if '\x1a' in lines1[-1]:
    # \x1a byte was found, remove the last item from list
    del lines1[-1]

如果我可以提供建议,那么所有代码​​块都会重复。您可以创建一个捕获所有功能的函数,然后将文件名传递给它。

def process_csv(file_name):
    # Open the file for both reading and writing
    # This will also automatically close the file handle after
    # you're done with it
    with open(file_name, 'r+') as csv_file:
        data = csv_file.readlines()
        if '\x1a' in data[-1]:
            # erase file and then write data without last row to it
            csv_file.seek(0)
            csv_file.truncate()
            csv_file.writelines(data[:-1])
        else:
            # Just making this explicit
            # Don't do anything to the file if the \x1a byte wasn't found
            pass

for f in ('sdn.csv', 'add.csv', 'alt.csv'):
    process_csv(f)