我正在使用 Google Colab 执行以下任务,但它不起作用。当我在少于 10 个文件的小文件夹上进行测试时,我的脚本运行良好;但是,它们不适用于具有数千个文件的较大文件。在旁注中,我无法确定文件夹的大小,因为 Google Drive 没有这样的选项。
希望知道原因和解决方法。太感谢了!
任务 #1:将所有 json 文件从一个文件夹移动到 Google Drive 上的另一个文件夹。当我在较小的文件夹上进行测试时。所有文件都按预期移动。但是,当用于具有更大尺寸的“真实文件夹”时,它看起来好像有效。没有超时。但是当我查看 Google Drive 上的文件夹时,文件仍然存在。没有改变。
source = glob.glob('/path_to_source_folder/*.json')
destination = '/path_to_destination_folder/'
for json_file in source:
id = os.path.basename(json_file)
file = '/path_to_destination_folder/{}'.format(id)
if os.path.exists(file):
print('The file {} already exists'.format(id))
os.remove(json_file)
else:
shutil.move(json_file, destination)
任务 #2:获取文件夹和 json 文件的统计信息。我在较小的文件夹上进行了测试,效果很好。旁注:较小文件夹上的 json 文件与较大文件上的 json 文件具有相同的结构。当涉及到较大的文件夹时,它没有超时。结果是“0”。像“0 个用户”、“0 个帖子”等。这些肯定是错误的。
files = glob.glob('/path_to_reference_folder/*.json')
total_users = 0
not_empty_users = 0
total_posts_by_users = []
for file in files:
total_users += 1
with open(file, 'r') as f:
tmp = f.readlines()
if len(tmp) > 0:
not_empty_users += 1
total_posts_by_users.append(len(tmp))
print("total {} users".format(total_users))
print("total {} posts by users".format(np.sum(total_posts_by_users)))
print("total {} users not empty".format(not_empty_users))
print("total {} average posts per users".format(np.mean(total_posts_by_users)))
注意:早期步骤 - 安装驱动器和导入库
# Mounting Drive
from google.colab import drive
drive_mounting = drive.mount('/content/drive')
# Importing libraries
import numpy as np
import os
import glob
import json
import shut