我在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)
答案 0 :(得分:2)
您可以做的是使用Pandas
,因为它可以实现DataFrame操作。
file.csv
1,2,3,4,5
1,2,3,4,5
1,2,3,4,5
您的代码应类似于
import pandas as pd
df = 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)
file.csv
2,3,4,5
2,3,4,5
2,3,4,5