文件夹名称作为列名称之一

Folder name as one of the column names

我在 100 多个文件夹中有 1000 多个文件。我需要将文件夹的名称之一作为列之一写入文件。

目录结构:

Data -> 000 -> Trajectory -> set of files
Data -> 001 -> Trajectory -> set of files
Data -> 002 -> Trajectory -> set of files
Data -> 003 -> Trajectory -> set of files
.        .        .
.        .        .
.        .        .
Data -> nnn -> Trajectory -> set of files

每个Trajectory文件夹都有100多个文件,每个文件都有以下列。每个文件都有一个扩展名 .plt

39.984702,116.318417,0,492,39744.1201851852,2008-10-23,02:53:04
39.984683,116.31845,0,492,39744.1202546296,2008-10-23,02:53:10
39.984686,116.318417,0,492,39744.1203125,2008-10-23,02:53:15
39.984688,116.318385,0,492,39744.1203703704,2008-10-23,02:53:20
39.984655,116.318263,0,492,39744.1204282407,2008-10-23,02:53:25
39.984611,116.318026,0,493,39744.1204861111,2008-10-23,02:53:30

我试图将文件夹名称作为列名称之一。

预期输出:文件夹中名称为 000

的文件
000 39.984702,116.318417,0,492,39744.1201851852,2008-10-23,02:53:04
000 39.984683,116.31845,0,492,39744.1202546296,2008-10-23,02:53:10
000 39.984686,116.318417,0,492,39744.1203125,2008-10-23,02:53:15
000 39.984688,116.318385,0,492,39744.1203703704,2008-10-23,02:53:20
000 39.984655,116.318263,0,492,39744.1204282407,2008-10-23,02:53:25
000 39.984611,116.318026,0,493,39744.1204861111,2008-10-23,02:53:30

我找不到附近的样本可以解决。任何建议都会有所帮助。

编辑 1: 正如@EdChum 关于使用 glob 的建议,但这只允许我找到具有给定扩展名的文件。但我的问题是另外一回事。

用更简单的话来说

rootdir -> subdir_1 -> subdir_2 -> files

subdir_1 的名称作为 col[0] 包含在 subdir_2 中存在的所有文件中以及其他列中。无需创建新的输出文件即可附加文件。

  • 第一段代码将获取所有以.plt
  • 结尾的文件
  • 接下来,我们检查您的 subdir_1 是否实际上仅由数字组成且字符长度(只是一些完整性检查以确保我们不会命中所有以 .plt 结尾的文件)以及是否plt 文件位于轨迹文件夹中。
  • 最后,打开一个与原始文件同名的新文件,但附加了 .new。读取旧文件中的每一行,在开头添加一个具有目录名称的新列,并将新行写入输出文件。


import os

#get all plt files
traj_files = []
for root, dirs, files in os.walk('Data'):
    for filename in files:
        if filename.endswith('.plt'):
            traj_files.append(os.path.join(root, filename))

for traj_file in traj_files:

    #the new column we want to write
    new_col = traj_file.split('/')[1]
    #check if filename looks OK
    if len(new_col) != 3 or not new_col.isnumeric() or not '/Trajectory/' in traj_file:
        continue

    #read old file and write new column
    with open(traj_file + '.new', 'w') as new_traj:
        with open(traj_file, 'r') as old_traj:
            for line in old_traj.readlines():
                new_traj.write(new_col + ' ' + line)

肯定有更灵活和优雅的方法,但这应该适用于您的特定目录结构。