我有一个文件夹,里面装满了很多 zip 文件夹。每个 zip 内有 1 到 4 个 CSV 文件。我想创建一个目录(最好打印为 Excel),其中第 1 列包含 zip 文件夹名称中的数字,第 2 列包含其中包含的至少 1 个 csv 文件的名称的一部分那个 zip 文件夹。因此,读取每个 csv 文件中至少一个的路径名并保存其中的两个文件就可以了。
更多详情:
Zip 文件夹: zip 文件夹的命名方案如下:“CSV_2023_Q2_XXXXXXX_XXXXXXX.ZIP”。其中有 3,000 多个。
每个 Zip 中都有 CSV 文件: 每个 Zip 文件夹中都有 1 到 4 个 csv 文件。这些都遵循一致的命名方案 文件名的开头,但具有(最多)4 个不同的后缀。这 根目录如下:“202306_COMPANY_NAME_LLC...”(公司注意事项 他们的名字中多于或少于两个单词,它将有一个 不同的结构,如“202306_COMPANY...”或 “202306_COMPANY_WITH_LONG_NAME_LLC...”)。这些 csv 的后缀 文件是“_ident.CSV”、“_contracts.CSV”、“_indexPub.CSV”和 “_transactions.CSV”。例如,完整的 csv 文件名将是: “202306_COMPANY_NAME_LLC_ident.csv”。所有 zip 文件夹至少有 “ident.csv”文件,但并非所有文件都有其余部分。
最终目标:我想遍历所有这些 zip 文件夹并创建一个将 zip 文件夹的名称链接到公司的目录 里面的名字。只要这个目录是可搜索的,我就不会 关心它是如何构建的,但我更喜欢它是否可以输出到 Excel 文件。
谢谢!!
我已经尝试了以下方法,但我得到的只是一个最终的 csv 文件,其中只有列标题的标题:
# I first imported the path of the folder as main_folder
folder_file_info = []
# Traverse the main folder
for root, dirs, files in os.walk(main_folder):
for folder_name in files:
if folder_name.startswith("CSV_"):
zip_folder_path = os.path.join(root, folder_name)
# Get the list of files in zip folders
zip_files = []
with zipfile.ZipFile(zip_folder_path, "r") as zip_ref:
zip_files = zip_ref.namelist()
# Find Ident file
ident_file = next((file for file in zip_files if file.endswith("_ident.csv")),None)
if ident_file:
# Extract company name
zip_folder_name = folder_name
file_beginning = ident_file.rsplit("_ident.csv",1)[0]
folder_file_info.append((zip_folder_name,file_beginning))
#Write folder and file info into a CSV
csv_file_path = "folder_contents_6.csv"
with open(csv_file_path, "w",newline="") as csv_file:
csv_writer = csv.writer(csv_file)
csv_writer.writerow(["Zip Folder", "Company Name"])
csv_writer.writerows(folder_file_info)
from multiprocessing.dummy import Pool
from pathlib import Path
import csv, zipfile
# function for worker threads
def worker(filename):
with zipfile.ZipFile(filename) as file:
ident = (i for i in file.namelist() if i.endswith('_ident.csv'))
files = ', '.join(i.rsplit('_ident.csv', 1)[0] for i in ident)
return (filename, files or 'no "_ident.csv" found')
if __name__ == '__main__':
# use pathlib to make a list of filenames
# adjust path as needed
csv_files = (file.resolve() for file in Path('.').glob('CSV_*'))
# might get a slight bump from multiple threads, might not
with Pool() as pool:
# if order matters, use imap
# imap_unordered returns results "as completed"
results = [result for result in pool.imap_unordered(worker, csv_files)]
pool.join()
with open('folder_contents_6.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['zip_folder', 'company_name'])
writer.writerows(results)