要查找CSV文件中上次出现的特定行,可以使用Python的csv
模块来读取文件,并结合文件指针的位置来实现。以下是一个详细的步骤和示例代码:
以下是一个示例代码,展示如何查找CSV文件中上次出现的特定行:
import csv
def find_last_occurrence(file_path, target_row):
last_position = None
found = False
# 尝试读取上次记录的位置
try:
with open('last_position.txt', 'r') as pos_file:
last_position = int(pos_file.read())
except FileNotFoundError:
pass
with open(file_path, 'r') as csvfile:
csvreader = csv.reader(csvfile)
# 如果有上次记录的位置,跳到该位置
if last_position is not None:
csvfile.seek(last_position)
for row in csvreader:
if row == target_row:
found = True
break
# 记录当前位置
last_position = csvfile.tell()
# 保存当前位置
with open('last_position.txt', 'w') as pos_file:
pos_file.write(str(last_position))
return found
# 示例使用
file_path = 'example.csv'
target_row = ['John', 'Doe', '30']
result = find_last_occurrence(file_path, target_row)
print(f"Last occurrence found: {result}")
last_position.txt
来记录上次读取的位置。seek
方法跳到该位置。last_position.txt
中。csv.Sniffer
来自动检测CSV格式。pandas
)。import csv
def find_last_occurrence(file_path, target_row):
last_position = None
found = False
try:
with open('last_position.txt', 'r') as pos_file:
last_position = int(pos_file.read())
except FileNotFoundError:
pass
with open(file_path, 'r') as csvfile:
csvreader = csv.reader(csvfile)
if last_position is not None:
csvfile.seek(last_position)
for row in csvreader:
if row == target_row:
found = True
break
last_position = csvfile.tell()
with open('last_position.txt', 'w') as pos_file:
pos_file.write(str(last_position))
return found
file_path = 'example.csv'
target_row = ['John', 'Doe', '30']
result = find_last_occurrence(file_path, target_row)
print(f"Last occurrence found: {result}")
通过这种方式,可以高效地查找CSV文件中上次出现的特定行,并确保在大文件情况下也能有效处理。
领取专属 10元无门槛券
手把手带您无忧上云