【问题标题】:Delete a row from a CSV where input matches in column [closed]从CSV中删除列中输入匹配的行[关闭]
【发布时间】:2016-04-28 17:01:50
【问题描述】:

我将如何从 txt 文件中删除键和键值?例如,如果用户想从此文件中删除一个叫 Sarah 的人:

Joe,Bloggs,J.bloggs@example.com,01269 512355, 1, 0, 0, 0,
Sarah,Brown,S.brown@example.com,01866 522555, 1, 0,  0, 0,
…

目前我有以下:

L = open("players.txt","r+")

delete_name1 = raw_input ("Enter the first name of the person you wish to delete: ")
for line in L:
    s = line.strip()
    string = s.split(",")
    if delete_name1 == string[0]:
        del string[:8] # Doesn't work
        print delete_name1 + " has been deleted."
L.close() # Closes the file to free us usage space.

代码被接受,但不会更改 txt 文件。我觉得我必须将更新后的信息写回 txt 文件,但我不知道该怎么做。

Please select an option: 2
Enter the first name of the person you wish to delete: Sarah
Sarah has been deleted

【问题讨论】:

  • 这个问题太笼统了。提供您当前的尝试并描述您遇到的问题。
  • 欢迎!请查看stackoverflow.com/help/how-to-ask。您也可以编写一个文本文件外观的示例。到目前为止你做了什么,你不明白什么?
  • 将整个文件存储到某个数据结构中,从数据结构中删除Sarah的信息,然后将整个数据结构写回文件中。
  • 感谢你们的快速帮助。珍惜你的时间。我会按照你们所说的,看看它是否有效。

标签: python csv file-io


【解决方案1】:

如果文件很小,只需重新写入整个文件。对于文本文件和内置函数,这是一个简单的方法:

with open(filename) as input_file:
    data = []
    for line in input_file:
        if not line.startswith("Sarah,Brown"):
            data.append(line)

with open(filename, 'w') as output_file:
    for d in data:
        output_file.write(d + '\n')

【讨论】:

    【解决方案2】:

    要修改文件,您必须完全覆盖该文件。这是一个简短的例子:

    newFile = []
    with open('test.txt', 'r') as f:
        lines = f.readlines()
        for line in lines:
            newFile.append(line.strip().split(',')[1:3])
    
    with open('test.txt', 'w') as f:
        for line in newFile:
            f.write(','.join(line) + '\n')
    

    使用输入文件运行它:

    1,Trevor,H
    2,Matt,D
    

    输出是:

    Trevor,H
    Matt,D
    

    【讨论】:

      猜你喜欢
      • 2012-07-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多