我想删除CSV文件中从第2行到特定数字的行,但它会删除文件中的所有行

2024-04-26 13:39:55 发布

您现在位置:Python中文网/ 问答频道 /正文

目前,它正在删除CSV中的所有内容,以及如何创建默认编号,以便它将从第2行删除到特定行

这就是我正在做的

import csv

user_input = input("Please enter a row name to be deleted.")
read = open('color.csv', 'rb')
write = open('color.csv', 'wb')
writer = csv.writer(write)

for row in csv.reader(user_input):

    if row == input:
        writer.writerow(row)
        read.close()
        write.close()
        
print('Used colors names deleted')

Tags: csvimport内容closereadinputopen编号
1条回答
网友
1楼 · 发布于 2024-04-26 13:39:55

主要原因是从文件中删除所有内容是因为您在读模式和写模式下打开了同一个文件。以写模式打开现有文件将完全清除该文件

相关文件:here

open(filename, mode):
The first argument is a string containing the filename. The second argument is another string containing a few characters describing the way in which the file will be used. mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased), [...]

(强调矿山)


您的代码还有很多其他问题:

  • input()存储在{}中-覆盖内置(您编辑了它,很棒:o))
  • 对文本文件打开的文件使用二进制模式
  • 在字符串上使用csv.reader(...)而不是文件句柄
  • 未对csv模块打开的文件使用newline=""
  • 未将所有数据写入新文件
  • 比较csvrow(列表)与作为字符串的user_input
  • 尝试打开同一个文件进行读写,并同时执行这两项操作
  • 不使用上下文处理程序进行文件操作

要修复它,请为输出打开另一个文件,读取输入文件,将行的第一个值与userinput进行比较,如果匹配,则跳过写入这一行

最后,请参阅csv中删除行的其他相关文章-您这里的问题不是重复,因为这些内容碰巧没有使用相同的名称覆盖手头的文件

创建csv演示文件:

with open ("color.csv","w") as f:
   for color in ['blue', 'crash', 'pink', 'gold', 'silver']:
       f.write(f"{color},some other,tabulars in the,csv\n")

过程文件:

"""This code deletes rows with a given 'color' in column 0"""
import csv

color_to_delete = "pink" # input("Please enter a row name to be deleted.")
# not binaryy - it is a CSV with is TEXT - and you need to supply newline=""
with open('color.csv', newline="") as r, open("2ndColor.csv","w", newline="") as w:  

    writeme = csv.writer(w)
    for row in csv.reader(r): # why input? you need the file handle
        if row[0] == color_to_delete:
            continue # skip this row
        writeme.writerow(row)

print("# before:")
print(open("color.csv").read())
print("\n# after:\n" + open("2ndColor.csv").read())

输出:

# before:
blue,some other,tabulars in the,csv
crash,some other,tabulars in the,csv
pink,some other,tabulars in the,csv
gold,some other,tabulars in the,csv
silver,some other,tabulars in the,csv


# after:
blue,some other,tabulars in the,csv
crash,some other,tabulars in the,csv
gold,some other,tabulars in the,csv
silver,some other,tabulars in the,csv

要在添加的InputedColor之后删除多行,请执行以下操作:

"""This code deletes rows with a given 'color' in column 0 and the following
'lines_to_deete' rows""" 

color_to_delete = "pink" # input("Please enter a row name to be deleted.")
lines_to_delete = 1  # will delete the pink line and 1 more
lc = 0

with open('color.csv', newline="") as r, open("2ndColor.csv","w", newline="") as w:      
    writeme = csv.writer(w)
    for row in csv.reader(r): # why input? you need the file handle
        if row[0] == color_to_delete:
            lc = lines_to_delete 
            continue # skip this row
        elif lc:
            lc -= 1
            continue
        writeme.writerow(row)

要获得以下内容的输出:

after:
blue,some other,tabulars in the,csv
crash,some other,tabulars in the,csv
silver,some other,tabulars in the,csv

要跳过某些行范围,可以执行以下操作:

import csv

lines_to_skip = range(2,5) # 2,3,4

with open('color.csv', newline="") as r, open("2ndColor.csv","w", newline="") as w:      
    writeme = csv.writer(w)
    # enumerate the input and skip row if in range
    for line_num, row in enumerate(csv.reader(r)): # why input? you need the file handle
        if line_num in lines_to_skip:
            continue # skip this row

        writeme.writerow(row)

要获得以下内容的输出:

after:
blue,some other,tabulars in the,csv
crash,some other,tabulars in the,csv

有关文件打开模式的说明,请参见Difference between modes a, a+, w, w+, and r+ in built-in open function?

相关职位:

相关问题 更多 >