如果 csv 文件超过 3 行,编辑它以删除第一行(不另存为新文件)

If the csv file is more than 3 lines, edit it to delete the first line (Not save as new file)

我正在尝试编码,如果 csv 文件超过 3 行,请编辑它以删除第一行。

我想从现有文件中删除第一行而不是将其另存为新文件。

出于这个原因,我不得不删除现有文件并创建一个同名但 只保存一行,逗号消失。

我正在使用 Pandas 数据框。不过不用也没关系,我也不想用

函数名可能有点奇怪,因为我是初学者

谢谢。

file = open("./csv/selllist.csv", encoding="ANSI")
reader = csv.reader(file)
lines= len(list(reader))


if lines > 3:
    df = pd.read_csv('./csv/selllist.csv', 'r+', encoding="ANSI")
    dfa = df.iloc[1:]
    
    print(dfa)

    with open("./csv/selllist.csv", 'r+', encoding="ANSI") as x:
        x.truncate(0)
    with open('./csv/selllist.csv', 'a', encoding="ANSI", newline='') as fo:  
        # Pass the CSV  file object to the writer() function
        wo = writer(fo)
        # Result - a writer object
        # Pass the data in the list as an argument into the writerow() function
        wo.writerow(dfa)  
        # Close the file object
        fo.close()
print()

这是我处理的csv文件类型

string, string, string, string, string
string, string, string, string, string 
string, string, string, string, string
string, string, string, string, string 

使用pandas,读写时只需指定header=None即可:

import pandas as pd

if lines > 3:
    df = pd.read_csv("data.csv", header=None)
    df.iloc[1:].to_csv("data.csv", header=None, index=None)

使用 csv 模块:

import csv

with open("data.csv") as infile:
    reader = csv.reader(infile)
    lines = list(reader)
    
if len(lines)>3:
    with open("data.csv", "w", newline="") as outfile:
        writer = csv.writer(outfile, delimiter=",")
        writer.writerows(lines[1:])

采用两步法。

打开文件阅读并统计行数。如果超过 3 行,re-open 文件(用于写入)并更新它。

例如:

lines = []
with open('./csv/selllist.csv') as csv:
  lines = csv.readlines()
if len(lines) > 3:
  with open('./csv/selllist.csv', 'w') as csv:
    for line in lines[1:]: # skip first line
      csv.write(line)

一次 open 调用并使用 seektruncate

设置

out = """\
Look at me
I'm a file
for sure
4th line, woot!"""
with open('filepath.csv', 'w') as fh:
    fh.write(out)

解决方案

我的目标是尽量减少我正在做的事情。我只会打开一个文件,而且只会打开一次。我只分一次

with open('filepath.csv', 'r+') as csv:
    top, rest = csv.read().split('\n', 1)  # Only necessary to pop off first line
    if rest.count('\n') > 1:               # If 4 or more lines, there will be at
                                           # least two more newline characters

        csv.seek(0)                        # Once we're done reading, we need to
                                           # go back to beginning of file

        csv.truncate()                     # truncate to reduce size of file as well
        csv.write(rest)