[Python] 纯文本查看 复制代码
import os
def prepend_filename_to_txt_files(folder_path="."):
for root, _, files in os.walk(folder_path):
for file in files:
if file.endswith(".txt"):
file_path = os.path.join(root, file)
file_name_without_ext = os.path.splitext(file)[0]
temp_file_path = f"{file_path}_temp.txt"
with open(file_path, 'r', encoding='utf-8') as original_file:
content = original_file.read()
with open(temp_file_path, 'w', encoding='utf-8') as temp_file:
temp_file.write(file_name_without_ext + "\n")
temp_file.write(content)
os.replace(temp_file_path, file_path)
if __name__ == "__main__":
folder_path = "." # 可以根据需要修改文件夹路径
prepend_filename_to_txt_files(folder_path)
|