excel写入
各位大佬,如何遍历一个文件夹里的所有excel文件,将里面的数据写入到另一个文件夹里的同名excel里(另一个文件夹里没有同名excel则新增一个excel){:9_221:}{:9_221:}{:9_221:} 你可以使用 os.listdir() 遍历文件夹中的所有文件,然后通过判断文件名是否为 Excel 文件来筛选出需要处理的文件。然后,你可以使用 pandas 库来读取和写入 Excel 文件。
以下是实现该功能的示例代码:
import os
import pandas as pd
# 源文件夹和目标文件夹路径
source_folder = '源文件夹路径'
target_folder = '目标文件夹路径'
# 遍历源文件夹中的文件
for filename in os.listdir(source_folder):
# 判断文件是否为Excel文件
if filename.endswith('.xlsx') or filename.endswith('.xls'):
# 构建源文件路径和目标文件路径
source_path = os.path.join(source_folder, filename)
target_path = os.path.join(target_folder, filename)
# 判断目标文件是否已存在
if os.path.exists(target_path):
# 读取目标文件中的数据
target_data = pd.read_excel(target_path)
# 读取源文件中的数据
source_data = pd.read_excel(source_path)
# 将源文件中的数据追加到目标文件中
target_data = target_data.append(source_data, ignore_index=True)
# 将合并后的数据写入目标文件
target_data.to_excel(target_path, index=False)
else:
# 如果目标文件不存在,直接将源文件复制到目标文件夹
os.rename(source_path, target_path)
请将代码中的 '源文件夹路径' 和 '目标文件夹路径' 替换为你实际的文件夹路径,然后运行代码即可实现将源文件夹中的 Excel 文件数据写入到目标文件夹中的同名 Excel 文件,如果目标文件夹中没有同名文件,则会创建一个新的 Excel 文件。 你可以使用Python的库 pandas 来读取和写入Excel文件, os 和 glob 来操作文件和文件夹。以下是一种可能的实现方法:
首先,确保你安装了必要的库。如果没有安装,你可以使用以下命令进行安装:
pip install pandas openpyxl
以下是一段简单的Python代码实现:
import os
import glob
import pandas as pd
src_folder = '/path/to/source/folder' # 这是源文件夹的路径
dst_folder = '/path/to/destination/folder' # 这是目标文件夹的路径
# 遍历源文件夹中的所有Excel文件
for src_file in glob.glob(os.path.join(src_folder, '*.xlsx')):
# 获取文件的基本名(无路径和扩展名)
base_name = os.path.basename(src_file)
file_name = os.path.splitext(base_name)
# 创建目标文件路径
dst_file = os.path.join(dst_folder, file_name + '.xlsx')
# 读取源文件中的数据
df = pd.read_excel(src_file)
# 如果目标文件已存在,读取其内容并附加新的数据;
# 否则,直接将数据写入新文件。
if os.path.exists(dst_file):
df_existing = pd.read_excel(dst_file)
df_combined = pd.concat(, ignore_index=True)
df_combined.to_excel(dst_file, index=False)
else:
df.to_excel(dst_file, index=False)
这段代码会遍历源文件夹中的所有.xlsx文件,对每个文件,它都会读取数据,检查目标文件夹中是否已存在具有相同名称的文件,如果存在,则将新的数据附加到现有数据中,否则,将创建一个新的文件并写入数据。
这段代码假设源文件和目标文件都是.xlsx格式,且所有源文件都可以直接以DataFrame的形式读取。如果实际情况不同,可能需要对代码进行适当修改。 isdkz 发表于 2023-7-12 11:08
你可以使用Python的库 pandas 来读取和写入Excel文件, os 和 glob 来操作文件和文件夹。以下是一种可能的 ...
# 否则,直接将数据写入新文件。
if os.path.exists(dst_file):
df_existing = pd.read_excel(dst_file)
df_combined = pd.concat(, ignore_index=True)
df_combined.to_excel(dst_file, index=False)
那大佬,如果目标文件已存在,要把他覆盖的话,这段应该怎么改 a1503818992 发表于 2023-7-12 13:55
# 否则,直接将数据写入新文件。
if os.path.exists(dst_file):
df_existing = pd.rea ...
如果你希望直接覆盖目标文件中的内容,而不是将新数据附加到旧数据上,你只需要在读取源文件后直接写入目标文件,无需检查目标文件是否存在。这样就会覆盖任何已存在的文件。
以下是相应部分的代码:
# 读取源文件中的数据
df = pd.read_excel(src_file)
# 将数据写入目标文件(覆盖已存在的文件)
df.to_excel(dst_file, index=False)
现在,无论目标文件是否已存在,都会被新数据覆盖。如果它不存在, to_excel 函数将创建一个新文件。 isdkz 发表于 2023-7-12 13:57
如果你希望直接覆盖目标文件中的内容,而不是将新数据附加到旧数据上,你只需要在读取源文件后直接写入目 ...
好的,谢谢大佬!
页:
[1]