如何从 CSV 文件和最后一行中的单行中删除特定数据?

How to delete specific data from single line in CSV FILE and last line?

我有一个 CSV 文件,我已使用以下代码成功删除了行:

    myfiles = glob.glob('myfile.csv')
    
    for file in myfiles:
        lines = open(file).readlines()
        open(file, 'w').writelines(lines[27:])

现在CSV文件中的内容如下:

"Football names", "F1", "F2", "F3", "F4", "F5", "F6", "F7", "F8", "F9", "F10"

"Football weights", "8", "10", "11", "120", "10", "21", "20", "1000", "2000", "3000"

"Copy of Football weights", "8", "10", "11", "120", "10", "21", "20", "1000", "2000", "3000"

我想做的事情:

我一直在尝试使用上面的代码编辑 CSV 文件以完全删除 第 6 行,但不知道如何将其添加到上面的代码以及编辑行2 和第 4 行 删除行 的最后 3 个三个内容(分别为 F8、F9、F10 和 1000、2000、3000)--> 因此 CSV 应如下所示:

"Football names", "F1", "F2", "F3", "F4", "F5", "F6", "F7"

"Football weights", "8", "10", "11", "120", "10", "21", "20"

如果有人能给我一些指点或提示,在此先感谢您。

您可以从 csv 文件创建数据框,并使用 drop 函数删除其中的列和行。

# Convert the dictionary into DataFrame 
df = pd.DataFrame(data)
  
# Remove last 3 columns.
new_df=df.drop(df.iloc[:, -3:], axis = 1)

# Remove last row.
new_df=df.drop(df.iloc[-1,:],axis=1)

使用csv模块读取和重写没有最后3列

for file in myfiles:
    rows = []

    with io.open(file,"r",encoding="utf-8") as f:
        reader = csv.reader(f, delimiter=",", quotechar='"')

        for row in reader:
            rows.append(row[:-3])

    with io.open(file,"w",encoding="utf-8") as f:
        writer = csv.writer(f)
        
        for row in rows:
            writer.writerow(row)

这是一个使用 csv 库的简单解决方案。

import csv

# myfiles = ['f1.csv', 'f2.csv']  # this is for my testing
myfiles = glob.glob('myfile.csv')

for file in myfiles:
    with open(file, 'r') as csvfile:
        lines = list(csv.reader(csvfile, quotechar='"'))  # Read input file
    with open(file, 'w') as csvfile:
        writer = csv.writer(csvfile)  # Write to the same file
        # Remove the last line (I don't know exactly if you need to)
        for line in lines[27: -1]:  # Remove -1 to keep the last line
            # Removing last three columns
            writer.writerow(line[: -3]) 

如果还有什么我可以帮忙的,请告诉我。