首页 > 解决方案 > 修改和操作目录和子目录中的多个 csv 文件

问题描述

我在要修改的文件夹和嵌套文件夹中有几个 csv 文件。

我怎样才能发现错误以及使它起作用的任何想法。

我试过这段代码。它不起作用。

import csv
import os

for root, subdir, files in os.walk('path'):
    for csvfiles in files:
        if csvfiles.endswith(".csv"):
            paths = os.path.join(root, csvfiles)
            with open(csvfiles, newline='') as input_file:
#read the input csv file
                reader = csv.reader(input_file)
                data = [line for line in reader]
#load the the output file
            with open(csvfiles, 'w', newline='') as output_file:
                writer = csv.writer(output_file)
#add the column name
                writer.writerow(['X', 'Y', 'Width', 'Height', 'Tag'])
                writer.writerows(data)

标签: pythonpython-3.xcsvos.walk

解决方案


打开文件时将csvfiles变量更改为。paths

import csv
import os

for root, subdir, files in os.walk('path'):
    for csvfiles in files:
        if csvfiles.endswith(".csv"):
            paths = os.path.join(root, csvfiles)
            with open(paths, newline='') as input_file:
#read the input csv file
                reader = csv.reader(input_file)
                data = [line for line in reader]
#load the the output file
            with open(paths, 'w', newline='') as output_file:
                writer = csv.writer(output_file)
#add the column name
                writer.writerow(['X', 'Y', 'Width', 'Height', 'Tag'])
                writer.writerows(data)

推荐阅读