python - 修改和操作目录和子目录中的多个 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)
解决方案
打开文件时将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)
推荐阅读
- javascript - 如何在d3.js中制作信息框并附上图表
- php - 如何将逗号从 laravel 表单添加到单独的行中?
- html - 使用 Bulma 将侧边栏上的菜单(不是导航)转换为小屏幕中的“汉堡”菜单
- azure-iot-sdk - 通用 Windows 项目,VS17,无法安装 Microsoft.Azure.Devices.Client IOT SDK
- java - 如何将两个列表转换为对象列表
- javascript - 为什么重命名对象的键会失去价值?
- android - Android 托管设备卡在 KIOSK 模式,政策不会自动应用,无法取消固定
- discord.py-rewrite - Discord.py 重写自定义帮助 通过 Cog 嵌入排序命令
- json - Jolt 规范将元素数组转换为具有 id 的对象
- sql - 使用 SQL Server 查找差异实例的数量