Skip to main content
 首页 » 编程设计

python之从文件路径创建逗号分隔值文件

2025年05月04日9rubylouvre

我正在使用 python 创建一个 CSV(逗号分隔值)文件。它包含文件夹中的路径和所有文件。文件在不同的文件夹中,以逗号分隔,然后是其文件夹的编号,无字符。例如,我有图像 1.pgm 存储在文件夹 s14 中。然后 CSV 格式看起来像

at/s14/1.pgm;14 

其中,at/s14/1.pgm是文件1.pgm的完整路径,14是数字(称为标签)从其文件夹 s14 中获取。你能帮我用python实现吗。我尝试使用该代码,但它不适用于我的任务

请您参考如下方法:

试试这个:

import os 
import re 
import sys 
 
 
 
SEPARATOR = ';' 
CSV_FILE_PATH = 'output.csv' 
 
 
 
if __name__ == "__main__": 
    if len(sys.argv) != 2: 
        print "usage: create_csv <base_path>" 
        sys.exit(1) 
 
    path = sys.argv[1] 
 
    # only folders in specified folder 
    folders = filter(os.path.isdir, os.listdir(path)) 
 
    with open(CSV_FILE_PATH, 'w') as csv_file: 
        for folder in folders: 
            # folder path 
            folder_path = os.path.join(path, folder) 
 
            # extracting number 
            match = re.match(r's(\d+)', folder) # s\d+ is the pattern of your folder name, for example s20 
            if match is not None: 
                number = match.group(1) 
 
                # loop for files within the folder 
                for filename in os.listdir(folder_path): 
                    # full file path 
                    filepath = os.path.join(folder_path, filename) 
 
                    # writing result 
                    line = SEPARATOR.join((filepath, number)) 
                    csv_file.write(line + '\n')