如何检测文本文件中已保存的链接

时间:2019-06-24 09:23:58

标签: python-3.x

所以我做了一个非常简单的程序,将链接保存到文本文件,我希望它告诉我是否尝试保存已经存在的链接,但是不会!我在做什么错了?

import os

space = " "

Links_lst = []

Links_i_saved = "Links i saved2.txt"

current_directory = os.listdir(os.getcwd())
if Links_i_saved in current_directory:
    with open(Links_i_saved, "r") as f:
        for i in f.readlines():
            if "Link: " in i:
                Links_lst.append(i.split("Link: ")[1])
            else:
                Links_lst.append(i)

while True:
    inpt = input("Give us a link (type 'break' to exit): ")
    if inpt == "break":
        break        
    else:
        if len(inpt) > 0:
            with open(Links_i_saved, "a+") as f:
                if inpt not in Links_lst:
                    if "." in inpt:
                        f.write("\n" + inpt.split(".", 2)[1] + space * (15 - len(inpt.split(".", 2)[1])) + space * 5 + "Link: " + inpt)
                    else:
                        f.write("\n" + inpt + space * (15 - len(inpt)) + space * 5 + "Link: " + inpt)
                    Links_lst.append(inpt)
                else:
                    print("You already saved this one!")
        else:
            print("No empty strings please!")

我要说“您已经保存了这个!”当链接已经存在,但除非我尝试在程序运行时将其保存两次,否则它将不会保存(我不想使用.read(),因为例如,如果我有链接,它将“检测” www.google.com)保存的所有Google URL)

1 个答案:

答案 0 :(得分:1)

如果尝试打印已保存的链接,您会注意到链接前面有尾随空格\r\n。这些空格导致此错误。

尝试以下代码:

import os

space = " "
Links_lst = []
Links_i_saved = "Links i saved2.txt"
current_directory = os.listdir(os.getcwd())

if Links_i_saved in current_directory:
    with open(Links_i_saved, "r") as f:
        for i in f.readlines():
            if "Link: " in i:
                Links_lst.append((i.split("Link: ")[1]).rstrip())
            else:
                Links_lst.append(i)

print(Links_lst)

while True:
    inpt = input("Give us a link (type 'break' to exit): ")
    if inpt == "break":
        break        
    else:
        if len(inpt) > 0:
            with open(Links_i_saved, "a+") as f:
                if inpt not in Links_lst:
                    if "." in inpt:
                        f.write("\n" + inpt.split(".", 2)[1] + space * (15 - len(inpt.split(".", 2)[1])) + space * 5 + "Link: " + inpt)
                    else:
                        f.write("\n" + inpt + space * (15 - len(inpt)) + space * 5 + "Link: " + inpt)
                    Links_lst.append(inpt)
                else:
                    print("You already saved this one!")
        else:
            print("No empty strings please!")