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

标签 python csv file delete-row readlines

我有一个 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 模块读取并重写回最后 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)

关于python - 如何删除CSV文件中单行和最后一行的特定数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68375880/

相关文章:

c# - 在最后一行之后插入行到 csv 文件

security - Delphi:从另一台计算机打开文件

python - 如何在Python中将标题行复制到新的csv

python - 如何创建根据文件名标记非结构化数据集的 csv 文件

python - 假设解密 key 被很好地隐藏,如何加密 python 模块

javascript - 如何在不使用 multipart 的情况下使用 AJAX 上传文件?

python - 如何在 python 中遍历 map 的元素

python - Nuitka编译PyQt5脚本时出现错误 "implicit module sip"错误

python - 使用 Tkinter 中的按钮导航到应用程序的不同页面?

python - 在 tensorflow 中手动创建 3+ 阶张量