【问题标题】:removing duplicate id entry from text file using python使用python从文本文件中删除重复的id条目
【发布时间】:2022-01-18 05:45:15
【问题描述】:

我有一个包含这些数据的文本文件(项目对应于代码、入口1、入口2):

a,1,2
b,2,3
c,4,5
....
....

这里的a,b,c.. 永远是独一无二的

每次我在 python 中读取此文件以创建一个新条目(例如 d,6,7)或更新现有值时:例如 a,1,2a,4,3

我使用以下代码:

data = ['a',5,6]
datastring = ''
        for d in data
            datastring = datastring + str(d) + ','
        try:
            with open("opfile.txt", "a") as f:
                f.write(datastring + '\n')
            f.close()
            return(True)
        except:
            return(False)

这会将任何数据附加为新条目。 我正在尝试这样的方法来检查每行的第一个字符:

f = open("opfile.txt", "r")
        for x in f:
            if(x[0] == username):
               pass

我不知道如何组合这两个,以便对第一个字符进行检查(让我们说它作为 id),如果文件中已经有一个带有 id 的条目,那么应该用新数据替换它并且所有其他数据保持不变,否则它将作为新行项目输入。

【问题讨论】:

  • for d in d:ata 应该是什么意思?那应该是for d in data: 吗?你要把data = 'a,5,6' 改成datastring = 'a,,,5,,,6,'——你为什么要那样做?
  • 抱歉打错了
  • 你为什么要循环遍历data 中的字符?
  • 这是我编码数据时的错误....数据将是一个列表
  • 然后使用datastring = ','.join(data)

标签: python python-3.x file


【解决方案1】:

将文件读入使用第一个字段作为键的字典中。更新相应的字典,然后将其写回。

使用csv 模块解析和格式化文件。

import csv

data = ['a',5,6]

with open("opfile.txt", "r", newline='') as infile:
    incsv = csv.reader(infile)
    d = {row[0]: row for row in incsv if len(row) != 0}

d[data[0]] = data

with open("opfile.txt", "w") as outfile:
    outcsv = csv.writer(outfile)
    outcsv.writerows(d.values())

【讨论】:

    【解决方案2】:

    首先将所有新行追加到文件中。

    其次,尝试使用 write 来更新文件中的行

    def update_record(file_name, field1, field2, field3):
        with open(file_name, 'r') as f:
            lines = f.readlines()
        with open(file_name, 'w') as f:
            for line in lines:
                if field1 in line:
                    f.write(field1 + ',' + field2 + ',' + field3 + '\n')
                else:
                    f.write(line)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 2021-04-09
      • 2017-03-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多