【问题标题】:python: read from .txt and judge the new string in the txt filepython:从.txt中读取并判断txt文件中的新字符串
【发布时间】:2018-05-08 06:20:04
【问题描述】:

我正在尝试读/写 txt 文件。我想从txt文件中读取,如果原始文件中不存在该字符串,则将新字符串写入下一行。

f = open('./video/1.txt', 'a')
f.write('123' + '\n')
f.close()

with open('./video/1.txt') as o:
    lines=o.readlines()

lines=set(lines)

if '123' in lines:
    print("Existed")
else:print("Not Existed")

问题是:我有 '123' 是 1.txt 文件。结果是“不存在”我尝试使用

for line in lines:
    print(line + '\n')

要打印出设置的变量“lines”,它会在一行打印出 123。我现在很困惑。是什么导致“不存在”?谢谢。

更新:我上传了截图。还是一头雾水。

【问题讨论】:

    标签: python python-3.x


    【解决方案1】:

    您的 if 语句正在检查 set lines 的元素是否为 '123'

    示例:

    lines = ['hello there', 'hello 123 there', '123']
    if '123' in lines:
        print("Existed")
    else:print("Not Existed")
    

    输出:

    Existed
    

    示例:

    lines = ['hello there', 'hello 123 there']
    if '123' in lines:
        print("Existed")
    else:print("Not Existed")
    

    输出:

    Not Existed
    

    你可以这样做:

    lines = ['hello there', 'hello 123 there']
    for line in lines:
        if '123' in line:
            print('Existed')
    

    如果您正在从文件中读取,您可能会在您的行中得到一个尾随回车符,这是\n。这也可能导致您的if '123' in lines 出错,即使该行仅是“123”,但实际上该行实际上是“123\n”。

    示例:

    ms = '123\n'
    print(ms)
    mb = ms.encode()
    print(mb)
    

    输出:

    123
    
    b'123\n'
    

    在此示例输出以及您的屏幕截图中,您实际上可以在输出中看到额外的回车符。因此你的字符串不是'123'你的字符串是'123\n'

    【讨论】:

    • 我刚刚更新了问题,很抱歉造成误解。我希望现在清楚了。
    • 是的。我上传截图。我不确定现在是否清楚。
    • @XiChen 不要忘记勾选给 Edwin 努力的人投票点
    【解决方案2】:

    感谢@Edwin van Mierlo 的回答,我现在明白了。 这是 123 之后的 '\n'。因此,如果我使用 '123\n' 而不是 123,则表明存在。

    if '123\n' in lines:
        print("Existed")
    else:print("Not Existed")
    

    【讨论】:

      【解决方案3】:

      迟到的答案,但无论如何

      我将使用lines1而不是继续使用lines作为变量

      In [3]: with open('1.txt') as o:
         ...:     lines = o.readlines()
         ...:
      
      In [4]: lines1 = set(lines)
      

      如果您在lines1 上进行打印,这就是您得到的结果。

      In [5]: print(lines1)
      {'123\n'}
      

      这会带你去哪里?

      如果您希望继续使用您的集合,一个可能的解决方案是使用正则表达式在您的集合中查找 123。

      正则表达式\d+ 将查找数字。

      In [6]: import re
      
      In [7]: if re.search(r'\d+', str(lines1)):
         ...:     print('yes')
         ...: else:
         ...:     print('no')
         ...:
      yes
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-05-09
        • 2015-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-10
        • 1970-01-01
        相关资源
        最近更新 更多