在Python中从csv文件中删除第一列

7

我有以下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)

有很多种方法可以做到这一点。你导入了 csv 但是没有使用它? - SuperStew
是的,现在我注意到我没有使用它。 - Danny
1个回答

18

你可以使用 Pandas,因为它可以实现对DataFrame的操作。

file.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)

file.csv

:文件名为“file.csv”。
2,3,4,5
2,3,4,5
2,3,4,5

我尝试了这个,它保存了一个新文件,但第一列没有被删除。 - Danny
1
to_csv 函数中添加 index=False,并确保将删除的数据框分配给一个变量。 - Rolando cq
现在它可以工作了,谢谢! - Danny
2
它是 pd.read_csv 而不是 read_csv - Cyzanfar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接