可以使用 Python 的
os 和 glob 模块来合并目录夹下所有 .xlsx 文件。以下是一个示例代码:
python
import
os
import glob
# 目标目录
target_dir =
/path/to/target/directory
# 源目录
source_dir =
/path/to/source/directory
# 获取目录下所有的 `.xlsx` 文件
xlsx_files = glob.glob(
os.
path.join(source_dir,
*.xlsx))
# 遍历所有的 `.xlsx` 文件
for xlsx_file
in xlsx_files:
# 拼接源文件路径和目标文件路径
source_file =
os.
path.join(source_dir, xlsx_file)
target_file =
os.
path.join(target_dir, xlsx_file)
# 如果目标文件不存在,则创建它
if not os.
path.exists(target_file):
os.makedirs(
os.
path.dirname(target_file), exist_ok=True)
with
open(target_file,
w) as f:
f.
write()
# 将源文件内容复制到目标文件中
with
open(source_file,
r) as f:
content = f.
read()
with
open(target_file,
w) as f:
f.
write(content)
在上面的代码中,我们首先指定了目标目录和源目录。然后,我们使用 glob 模块获取源目录下所有的 .xlsx 文件,并遍历所有的文件。对于每个 .xlsx 文件,我们首先拼接源文件路径和目标文件路径。然后,我们检查目标文件是否已经存在,如果不存在,则使用 os.makedirs 函数创建目标文件的目录。接着,我们打开源文件并读取其内容,然后将其写入目标文件中。最后,我们关闭源文件和目标文件。
需要注意的是,上面的代码只是一个示例,实际情况可能会更加复杂。例如,如果目标目录中有多个 .xlsx 文件,我们需要根据文件名的不同来区分它们。此外,如果目标目录中有多个相同名称的 .xlsx 文件,我们需要根据文件内容的不同来区分它们。
免责声明:本站所有文章和图片均来自用户分享和网络收集,文章和图片版权归原作者及原出处所有,仅供学习与参考,请勿用于商业用途,如果损害了您的权利,请联系网站客服处理。
相关标签: