python-3.x - 打印 .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 行。
- .csv 中的倒数第三行
- .csv 中的倒数第二行
- .csv 中的最后一行
解决方案
阅读所有行,然后打印最后三行:
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
推荐阅读
- jquery - 需要一个带有输入的 HTML5 Canvas 的 XY 坐标的 if 语句
- r - 从不同样本的两个回归中找到回归的 beta
- ajax - admin-ajax.php 偶尔返回 404 状态码
- javascript - 在 setTimeout 中调用的函数不使用当前的 React 状态
- python - 在 TensorFlow 中使用正则化和量化图
- angular - Angular 7 动态可注入模板
- linux - 在进行额外循环时
- mysql - 如何在 MySQL 中更改 SHOW GRANTS 标题?
- c# - Newtonsoft.Json filtering output
- javascript - 无输出 fast-csv writeToPath