我对python很新,并且有一个问题。我想读取多个csv文件,检查标题并比较文件的标题。
from tkinter import Tk
from tkinter.filedialog import askopenfilenames
import csv
root = Tk()
files= askopenfilenames(parent=root, title='Choose files')
for i in range(len(files)):
f = open('{}'.format(files[i]))
reader = csv.DictReader(f)
row = next(reader)
这是我已有的代码。我的问题是我不知道如何阅读文件的标题并进行比较。
我试过
row[i] = next(reader)
但那不起作用。
答案 0 :(得分:1)
简单的Python示例,它读取一堆文件并比较它们的标题。
last_header = None
# Loop through the files
for file in files:
with open(file) as f:
# Read the header
header = f.readline()
# If this is the first file, then store the
# header for later comparison
if last_header == None:
last_header = header
# Check that the header match the last header
elif header != last_header:
print("Some information to user")
quit()
# Read the remaining lines
lines = f.readlines()