【问题标题】:Placing a unique combinations into text file and detecting existing data将唯一组合放入文本文件并检测现有数据
【发布时间】:2021-05-23 16:31:27
【问题描述】:

这是我在文本文件中写入数据的代码。

        with open('CodeList.txt') as f:
            if (strCode) in f.read():
                print ("The product code already exist")
           
            else:
                print ("The product code bas been added successfully")
                with open('CodeList.txt','a+') as g:
                   g.write(strCode +"\n")

写入文本文件的字符串有一个从 A 到 L 的字符,例如“ABCDE” 它首先通过检查文本文件来检测字符串是否已经添加。

当我运行代码时,第一个条目是“ABCD”。这运行成功。 但是,当我想在文本文件中添加“ABC”时,它会失败,因为它检测到上一个条目中的“ABC”。

我对 Python 还是很陌生。非常感谢您的帮助!

【问题讨论】:

  • f.readlines()
  • 经过几次测试后不起作用。它只是不断将数据添加到新行中。

标签: python python-3.x readfile


【解决方案1】:

这是因为您将文件作为单个字符串而不是单独的行来处理。

试试这个:

if strCode in f.read().split("\n"):
    ...  

【讨论】:

  • readlines() 更可取,因为它一步完成工作,而不是 read()split()
  • 同意,但是你必须考虑到每行末尾烦人的 \n 。不过对于大文件,这将是值得的。
  • 我试过 f.readlines()。它没有检测到任何重复项。它只是不断添加到下一行。 f.read().split("\n"):效果很好。
  • 使用 readlines(),条件需要类似于 if strCode+"\n" in f.readlines():
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-07-05
  • 2021-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多