使用 Python 复制多个文件的内容并粘贴到主文件中
Using Python to copy contents of multiple files and paste in a main file
首先我会提到我对 Python 一无所知,但在线阅读它可以帮助我解决我的情况。
我想使用(我相信?)Python 脚本做一些事情。
我有一堆 .yml 文件,我想将它们的内容传输到一个主 .yml 文件中(我们称之为 Main.yml)。但是,我还希望能够获取每个单独的 .yml 的名称,并将其作为“##Name”添加到 Main.yml 的内容之前。如果可能,该脚本看起来就像目录中的每个文件,而不必列出我希望它查找的每个 .yml 文件(我的相关目录仅包含 .yml 文件)。不确定是否需要指定,但以防万一:我想将所有文件的内容附加到 Main.yml 并保持缩进(间距)。 P.S。我在 Windows
我想要的示例:
- 文件:Apes.yml
- 内容:
Documentation:
"Apes":
year: 2009
img: 'link'
在 运行 脚本之后,我的 Main.yml 想要:
##Apes.yml
Documentation:
"Apes":
year: 2009
img: 'link'
我也是 Python 的新手,所以这是一个很好的机会,可以看看我新学到的技能是否有用!
我想你想使用 os.walk 函数遍历目录中的所有文件和文件夹。
此代码应该有效 - 它假设您的文件存储在名为“文件夹”的文件夹中,该文件夹是您的 Python 脚本存储位置的子文件夹
# This ensures that you have the correct library available
import os
# Open a new file to write to
output_file = open('output.txt','w+')
# This starts the 'walk' through the directory
for folder , sub_folders , files in os.walk("Folder"):
# For each file...
for f in files:
# create the current path using the folder variable plus the file variable
current_path = folder+"\"+f
# write the filename & path to the current open file
output_file.write(current_path)
# Open the file to read the contents
current_file = open(current_path, 'r')
# read each line one at a time and then write them to your file
for line in current_file:
output_file.write(line)
# close the file
current_file.close()
#close your output file
output_file.close()
首先我会提到我对 Python 一无所知,但在线阅读它可以帮助我解决我的情况。
我想使用(我相信?)Python 脚本做一些事情。 我有一堆 .yml 文件,我想将它们的内容传输到一个主 .yml 文件中(我们称之为 Main.yml)。但是,我还希望能够获取每个单独的 .yml 的名称,并将其作为“##Name”添加到 Main.yml 的内容之前。如果可能,该脚本看起来就像目录中的每个文件,而不必列出我希望它查找的每个 .yml 文件(我的相关目录仅包含 .yml 文件)。不确定是否需要指定,但以防万一:我想将所有文件的内容附加到 Main.yml 并保持缩进(间距)。 P.S。我在 Windows
我想要的示例:
- 文件:Apes.yml
- 内容:
Documentation:
"Apes":
year: 2009
img: 'link'
在 运行 脚本之后,我的 Main.yml 想要:
##Apes.yml
Documentation:
"Apes":
year: 2009
img: 'link'
我也是 Python 的新手,所以这是一个很好的机会,可以看看我新学到的技能是否有用!
我想你想使用 os.walk 函数遍历目录中的所有文件和文件夹。
此代码应该有效 - 它假设您的文件存储在名为“文件夹”的文件夹中,该文件夹是您的 Python 脚本存储位置的子文件夹
# This ensures that you have the correct library available
import os
# Open a new file to write to
output_file = open('output.txt','w+')
# This starts the 'walk' through the directory
for folder , sub_folders , files in os.walk("Folder"):
# For each file...
for f in files:
# create the current path using the folder variable plus the file variable
current_path = folder+"\"+f
# write the filename & path to the current open file
output_file.write(current_path)
# Open the file to read the contents
current_file = open(current_path, 'r')
# read each line one at a time and then write them to your file
for line in current_file:
output_file.write(line)
# close the file
current_file.close()
#close your output file
output_file.close()