如何解压文件并访问其中的所有文件夹和子文件夹并创建数据框?

How to untar a file and access all the folders and subfolders within it and create a dataframe?

我有一个电子邮件数据集。数据集本身为 2 GB,下载为 tar.gz 文件。当我在我的系统上解压它时,我得到一个名为 "maildr" 的文件夹。

当我进入 "maildr" 文件夹时,我有一个文件夹列表,每个文件夹代表一个用户。当我单击代表用户的文件夹时,我会得到更多子文件夹,例如 "inbox"、"sent mail"、"deleted mail" 等

现在,当我单击 "inbox" 时,我有一组包含实际电子邮件的文本文件。如何遍历文件夹和子文件夹并访问电子邮件并创建相关数据框是个问题。

好消息是我找到了一个类似的解决方案,但它是在 R 中,我发现在 python 中做同样的事情很困难。

if (!file.exists("enron_mail_20150507.tgz")) {
    untar("enron_mail_20150507.tgz")
}

emails <- list.files("maildir/", full.names = TRUE, recursive = 
TRUE)
emails <- emails[grep("/inbox", emails)]

我建议您为第一个文件夹创建一个数据框。 然后你应该将所有数据帧附加到第一个文件夹。

为了为一个文件夹创建一个数据框,例如在邮箱文件夹中执行:

# Put in your mailbox path of the current user where the text files are saved
mypath = "home/archid/..../mailbox"
setwd(mypath)

# Create list of text files
txt_files_ls = list.files(path=mypath, pattern="*.txt") 
# Read the files in, assuming comma separator
txt_files_df <- lapply(txt_files_ls, function(x) {read.table(file = x, header = T, sep =",")})
# Combine them
combined_df <- do.call("rbind", lapply(txt_files_df, as.data.frame)) 

然后你需要读取所有文件夹并附加到第一个数据框。您将需要一个 for 循环和追加命令:pandas.DataFrame.append.

另一种方法是制作一个 bash 脚本来读取每个文件夹,并为每个文件夹创建一个 *.csv 文件。然后您将合并所有 csv 文件。检查 csv 写入文件命令。