首页 > 解决方案 > 打印 .csv 文件的最后 3 行

问题描述

需要让这部分 python 以人类可读的格式打印出 .csv 文件末尾的各个行。整行的信息需要打印在自己的行上。

我尝试过使用“deque”,它会产生大量无用的字符括号和不需要的信息。每当我使用双端队列时都很难阅读。我已经得到它来打印最后一行,但我无法从它之前得到 2 个。

#This section is intented to test the code that would print the last 3 entries to the INV.csv.
#Code currently not working.
def EX1():
    #Tells the user what they are seeing.
    print("====-----EXPERIMENTAL SECTION-----====")
    print("This section tests the call back method for last 3 vehichles added to inventory.")
    print("")

    with open('INV.csv','r') as INQB: #Opens INV.csv as read only.
        lineA = INQB.readline()[-1] #Works just fine, as intended.
        lineB = INQB.readline()[-2] #Does not work.
        #lineC = INQB.readline()[-3] #Still doesn't work.

        print("Previously listed entries to the Inventory List are as follows:") #To tell user what they are reading.

        #Need these print commands to print 3rd 2nd and last entry line made to INV.csv.
        #These entries are msade by another defined area not shown here.
        #print(lineC)
        print(lineB)
        print(lineA)

        #This is to tell me that this area was reached when tested and didnt fail.
        print("Stuff was supposed to be there /\.")            
        print("") #Spacing for readability.

        INQB.close() #Closes it (If its not closed it gets crashy)
        starter() #Exits to other portions of the program.

我需要这个代码补丁来以人类可读的格式生成 .csv 的最后 3 行。

标签: python-3.xcsv

解决方案


阅读所有行,然后打印最后三行:

with open('INV.csv') as INQB:
    lines = INQB.readlines()  # Reads all lines into a list.

for line in lines[-3:]:  # slices the list for the last three entries.
    print(line,end='') # end='' because the lines already have newlines in them.

如果文件太大而无法读取所有行,则可以从末尾查找大于 3 最大长度行的数量。例如:

# Create a file with 100 lines in it to use for demonstration.
with open('INV.csv','w') as f:
    for line in range(100):
        f.write(f'line {line}\n')

# Now open the file and read three lines efficiently.
with open('INV.csv','rb') as f: # open in binary for seek operations
    # Lines created above were 10 bytes long max, go back more than 3x that
    f.seek(-50,2) # 2 means end-of-file
    lines = f.readlines()  # read only the last few lines of the file

for line in lines[-3:]:  # slice only the last three lines and display.
    print(line.decode(),end='') # decode the line to text since file was opened in binary.

输出:

line 97
line 98
line 99

推荐阅读