案列:从当前目录data依次读取5个人的微博txt文件,按照文件长度排好顺序并命名为1.txt,
2.txt等,然后依次把内容写入到D盘“sumdata”目录下sum.txt文件中。
import os
import shutil
# 定义当前目录和D盘sumdata目录
current_dir = './'
sumdata_dir = 'D:/sumdata'
output_file = os.path.join(sumdata_dir, 'sum.txt')
# 确保sumdata目录存在,不存在则创建
os.makedirs(sumdata_dir, exist_ok=True)
# 获取当前目录下所有相关微博txt文件
files = [f for f in os.listdir(current_dir) if f.startswith('person') and f.endswith('.txt')]
# 按照文件长度排序
sorted_files = sorted(files, key=lambda f: os.path.getsize(os.path.join(current_dir, f)), reverse=True)
# 写入到sum.txt文件中
with open(output_file, 'w', encoding='utf-8') as sum_file:
for index, file in enumerate(sorted_files, start=1):
# 重命名文件
new_filename = f"{index}.txt"
shutil.move(os.path.join(current_dir, file), os.path.join(current_dir, new_filename))
# 读取文件内容并写入sum.txt
with open(os.path.join(current_dir, new_filename), 'r', encoding='utf-8') as f:
content = f.read()
sum_file.write(content)
# 可以选择在每个微博内容之间添加分隔符,例如换行符
sum_file.write('\n')
# 打印完成信息
print("文件处理完成,内容已写入D盘sumdata目录下的sum.txt文件中。")
运行结果: