修改和操作目录和子目录中的多个 csv 文件

Modify and manipulate mutiple csv files in directories and subdirectories

我想修改文件夹和嵌套文件夹中的几个 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)

打开文件时将 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)