你可以使用Python的os模块和pandas库来实现这个功能。下面是一个示例代码:
import os
import pandas as pd
def check_excel_format(folder_path):
excel_files = []
for file_name in os.listdir(folder_path):
if file_name.endswith('.csv') or file_name.endswith('.xlsx'):
excel_files.append(file_name)
for file_name in excel_files:
file_path = os.path.join(folder_path, file_name)
try:
pd.read_csv(file_path)
print(f'{file_name} is a csv file.')
except pd.errors.ParserError:
try:
pd.read_excel(file_path)
print(f'{file_name} is an xlsx file.')
except pd.errors.ParserError:
print(f'{file_name} is not a valid Excel file.')
你可以调用check_excel_format
函数,并传入文件夹的路径作为参数。该函数将遍历文件夹中的所有文件,如果文件的扩展名是.csv
或.xlsx
,则会使用pandas
库尝试读取文件。如果能够成功读取,则说明文件是合法的Excel文件,并打印相应的提示信息。如果读取失败,则说明文件不是合法的Excel文件。
请注意,这个函数假设你已经安装了pandas
库。如果没有安装,可以使用以下命令来安装:
pip install pandas