Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/306.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从文本文件制作列表并比较列表_Python - Fatal编程技术网

Python 从文本文件制作列表并比较列表

Python 从文本文件制作列表并比较列表,python,Python,full.txt包含: www.example.com/a.jpg www.example.com/b.jpg www.example.com/k.jpg www.example.com/n.jpg www.example.com/x.jpg a.jpg k.jpg partial.txt包含: www.example.com/a.jpg www.example.com/b.jpg www.example.com/k.jpg www.example.com/n.jpg www.example

full.txt包含:

www.example.com/a.jpg
www.example.com/b.jpg
www.example.com/k.jpg
www.example.com/n.jpg
www.example.com/x.jpg
a.jpg
k.jpg
partial.txt包含:

www.example.com/a.jpg
www.example.com/b.jpg
www.example.com/k.jpg
www.example.com/n.jpg
www.example.com/x.jpg
a.jpg
k.jpg
为什么下面的代码不能提供期望的结果

with open ('full.txt', 'r') as infile:
        lines_full=[line for line in infile]

with open ('partial.txt', 'r') as infile:
    lines_partial=[line for line in infile]    

with open ('remaining.txt', 'w') as outfile:
    for element in lines_full:
        if element[16:21] not in lines_partial: #element[16:21] means like a.jpg
            outfile.write (element)  
所需的剩余.txt应包含不在partial.txt中的full.txt元素,具体如下所示:

www.example.com/b.jpg
www.example.com/n.jpg
www.example.com/x.jpg

此代码将在每行末尾包含换行符,这意味着它永远不会精确匹配
“a.jpg”
“k.jpg”

with open ('partial.txt', 'r') as infile:
    lines_partial=[line for line in infile]
换成

with open ('partial.txt', 'r') as infile:
    lines_partial=[line[:-1] for line in infile]
要去除换行符(
line[:-1]
表示“没有行的最后一个字符”)

您可以使用库:


你试过打印全行和部分行吗?结果如何?这样做相当危险,例如,您的最后一行可能会变成“k.jp”。查看此线程以获得从文件中读取行的更安全的方法-您的代码比我的代码提供了更高的速度,但结果不会被line@Roman分隔Pekar@leanne是的,错过了。writelines()不添加行分隔符“-”,因此必须手动添加