34、编写一个程序,使用 readlink 测试符号链接,如果是符号链接,输出箭头和目标值。
#!/usr/bin/perl
use strict;
use warnings;
use 5.010;
foreach my $file ( @ARGV ) {
print $file;
if( -d $file ) {
say '/'
} elsif( -x $file ) {
say '*'
} elsif( defined( my $target = readlink( $file ) ) ) {
say " --> $target";
}
}
35、编写一个程序,统计指定目录结构中每个目录下的文件、目录和符号链接的数量,并输出它们的平均数量和标准差。
以下是一个使用 Python 编写的程序,用于统计指定目录结构中每个目录下的文件、目录和符号链接的数量,并输出它们的平均数量和标准差:
import os
import math
def count_items_in_directory(dir_path):
file_count = 0
dir_count = 0
symlink_count = 0
for entry in os.scandir(dir_path):
if entry.is_file():
file_count += 1
elif entry.is_dir():
dir_count += 1
elif entry.is_symlink():
symlink_count += 1
return file_count, dir_count, symlink_count
def calculate_stats(counts):
n = len(counts)
if n == 0:
return 0, 0
total = sum(counts)
mean = total / n
variance = sum((x - mean) ** 2 for x in counts) / n
std_dev = math.sqrt(variance)
return mean, std_dev
def main(root_dir):
file_counts = []
dir_counts = []
symlink_counts = []
for root, dirs, files in os.walk(root_dir):
file_count, dir_count, symlink_count = count_items_in_directory(root)
file_counts.append(file_count)
dir_counts.append(dir_count)
symlink_counts.append(symlink_count)
file_mean, file_std_dev = calculate_stats(file_counts)
dir_mean, dir_std_dev = calculate_stats(dir_counts)
symlink_mean, symlink_std_dev = calculate_stats(symlink_counts)
print(f"文件平均数量: {file_mean:.2f}, 标准差: {file_std_dev:.2f}")
print(f"目录平均数量: {dir_mean:.2f}, 标准差: {dir_std_dev:.2f}")
print(f"符号链接平均数量: {symlink_mean:.2f}, 标准差: {symlink_std_dev:.2f}")
if __name__ == "__main__":
root_directory = input("请输入要统计的根目录路径: ")
if os.path.isdir(root_directory):
main(root_directory)
else:
print("输入的路径不是有效的目录。")
代码说明:
-
count_items_in_directory函数:该函数用于统计指定目录下的文件、目录和符号链接的数量。 -
calculate_stats函数:该函数用于计算给定列表中元素的平均值和标准差。 -
main函数:该函数遍历指定目录及其子目录,统计每个目录下的文件、目录和符号链接的数量,并调用calculate_stats函数计算平均值和标准差。最后输出结果。

最低0.47元/天 解锁文章

被折叠的 条评论
为什么被折叠?



