打印.csv文件的最后3行

时间:2019-05-26 01:05:39

标签: python-3.x csv

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

我尝试使用“ deque”,它产生大量无用的字符括号,并且不需要信息。每当我使用双端队列时,都很难阅读。 我已经得到它来打印最后一行,但是我不能再打印它的前两行了。

#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行。

  • .csv中的第三行
  • .csv中的第二行
  • .csv中的最后一行

1 个答案:

答案 0 :(得分:2)

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

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