python - 从 Python 中的 csv 文件中删除第一列
问题描述
我在 Python 中有以下代码从 in_folder 文件夹中的 csv 文件中删除第一行,然后将它们保存在文件夹 out_folder 中。现在我需要删除csv 文件的第一列。有谁知道如何做到这一点?
import csv
import glob
import os
import shutil
path = 'in_folder/*.csv'
files=glob.glob(path)
#Read every file in the directory
x = 0 #counter
for filename in files:
with open(filename, 'r') as fin:
data = fin.read().splitlines(True)
with open(filename, 'w') as fout:
fout.writelines(data[1:])
x+=1
print(x)
dir_src = "in_folder"
dir_dst = "out_folder"
for file in os.listdir(dir_src):
if x>0:
src_file = os.path.join(dir_src, file)
dst_file = os.path.join(dir_dst, file)
shutil.move(src_file, dst_file)
解决方案
您可以做的是使用Pandas
它可以实现 DataFrame 操作。
文件.csv
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
您的代码应如下所示
import pandas as pd
df = pd.read_csv('file.csv')
# If you know the name of the column skip this
first_column = df.columns[0]
# Delete first
df = df.drop([first_column], axis=1)
df.to_csv('file.csv', index=False)
文件.csv
2,3,4,5
2,3,4,5
2,3,4,5
推荐阅读
- mocking - 如何使用 phpunit 测试 IMAP 操作?
- sql - 表版本控制 - DML 和 DDL 跟踪更改并回滚到以前的版本
- javascript - 如何让外部函数(在 javascript 中)调用 html 中的 ID?
- webpack - VueJS 无法挂载组件
- ios - 无法弄清楚我的第一个 Appium ruby 测试中的错误
- r - 在 R 中复制 Excel =INDEX() 函数
- mysql - MySQL 中的 SQL 查询耗时过长
- r - 显示 ggplot2 热图的整个宽度并改善其外观,因为似乎两个图在分组后合并为一个
- github - 无法使用 Node-RED 推送到远程 git 存储库
- c# - 条件与内存分配的 C# 性能