gpt-4o-2024-05-13· OpenAI
WildChat-4.8M (AI2)
python代码读取excel文件,将sheet[0[中第一列第三列单元格内容提取保存txt文件,每格内容一行,空值不提取,重复内容跳过
- User
python代码读取excel文件,将sheet[0[中第一列第三列单元格内容提取保存txt文件,每格内容一行,空值不提取,重复内容跳过
- Assistant
你可以使用
pandas库来处理 Excel 文件,利用openpyxl或xlrd引擎来读取.xlsx文件。下面是一个示例代码,完成读取 Excel 文件的第一个工作表的第一列和第三列的内容,并将非空且不重复的内容保存至一个文本文件中,每个内容占一行。首先,确保你已经安装了
pandas和openpyxl,可以使用以下命令安装:pip install pandas openpyxl下面是完整的代码示例:
import pandas as pd def read_excel_and_save_to_txt(file_path, txt_path): # 读取Excel文件的第一个工作表 df = pd.read_excel(file_path, sheet_name=0, engine='openpyxl') # 提取第一列和第三列(pandas 是从0开始索引,也即是第0和第2列) column1 = df.iloc[:, 0] column3 = df.iloc[:, 2] # 合并两列数据并去重与去空值 combined_data = pd.concat([column1, column3]).dropna().drop_duplicates() # 将处理后的数据保存到txt文件中,每个内容占一行 with open(txt_path, 'w', encoding='utf-8') as f: for item in combined_data: f.write(f"{item}\n") # 示例使用 read_excel_and_save_to_txt('your_excel_file.xlsx', 'output.txt')你可以将
your_excel_file.xlsx替换为你的 Excel 文件的实际路径,将output.txt替换为你希望保存的文本文件路径。