在Python中按行写入CSV文件

nhn9ugyo  于 2023-04-18  发布在  Python
关注(0)|答案(1)|浏览(144)

我想读取目录中所有'mp4'文件的名称,我需要将每个文件的名称写在csv文件的行中。但问题是所有名称都写在不同的列中。我如何解决这个问题?

import csv
import os
Names = []
path_and_label =[]

for file in os.listdir("/mnt/storage/user/kinetics400/train_256/abseiling"):
    #path_and_label =[]
    if file.endswith(".mp4"):
        full_address = os.path.normpath(os.path.join("/mnt/storage_6TB/user/kinetics400/train_256/abseiling", file))

        

        path_components = full_address.split(os.sep)
        
        Label = path_components[6]
        path_and_label.append(full_address + ' ' + Label)
        
        
        with open('/mnt/storage/user/kinetics400/my_kinetics.csv', 'w+', newline ='') as f:
    
            writer = csv.writer(f, lineterminator='\n')


            writer.writerow(path_and_label)
            
            

f.close()
dfuffjeb

dfuffjeb1#

你非常接近了。试试下面的代码。我不知道你想用Label=path_component[6]打印什么,我已经注解掉了那部分。

import csv
import os
Names = []
path_and_label =[]

all_files = os.listdir("G:\\")    
csv_files = list(filter(lambda f: f.endswith('.mp4'), all_files))

with open('.\\theResultfile.csv', 'w+', newline='') as outfile:
    writer = csv.writer(outfile, lineterminator='\n')
    for file in csv_files:
            #path_and_label =[]    
                full_address = os.path.normpath(os.path.join("G:\\", file))
                path_components = full_address.split(os.sep)
            # Label= path_components[6]
                print(path_components[1])
                path_and_label.append(path_components)
                print(path_components)
                writer.writerow(path_components)         
print(path_and_label)

上面的代码将下面的结果写入csvfile

递归搜索路径的代码。

import csv
import os

searchDirPath = 'S:\\'
searchFileExt = '.txt'
searchResults =[]

with open('.\\theResultfile.csv', 'w+', newline='') as outfile:
    writer = csv.writer(outfile, lineterminator='\n')
    for root, dirs, files in os.walk(searchDirPath):
        for file in files:
            if file.endswith(".txt"):
             searchResults.append(os.path.join(root, file))
             print(os.path.join(root, file))
             writer.writerow(os.path.join(root, file))

相关问题