如何在python中拆分文件

时间:2016-09-23 13:31:06

标签: python list file split

我正在尝试拆分2个列表,比较它们并创建一个新列表,而没有成功比较2个列表中的项目。

让我们说吧 List_1.txt =

Failed = abc
Failed = hfi
Failed = kdi

和List_2.txt =

1:1:1 - jdsfjdf
2:2:2 - iidf
3:3:3 - abc
6:3:1 - hfi
8:2:1 - kdi
3:1:5 - dua
3:1:2 - dfh

我想比较这些列表并创建一个没有list_1条目的new_list2。

我试过的是:

treinrit = open('List_1', 'r')
lijna = treinrit.readlines()
treinrit.close()

annuleer_treinrit = open('List_2', 'r')
lijnb = annuleer_treinrit.readline()
annuleer_treinrit.close()

lijsta = []
lijstb = []

for a in lijna:
    clean = a.split(' - ')
    print(lijsta)

for b in lijnb:
    lijstb.append(lijnb.split(": "))

我无法让列表正确分割。我只需要比较每个文件的最后一位,但我不知道如何。

2 个答案:

答案 0 :(得分:1)

with open('File1', 'r') as f1:
    f1_stored = []
    for line in f1:
        f1_stored.append(line.split('=')[1].strip())
    with open('File2', 'r') as f2;
        output = []
        for line in f2:
            if not any(failed in line for failed in f1_stored):
                output.append(line)

使用output

做你想做的事

答案 1 :(得分:1)

像这样的东西

, 1)

列表public class Regex { public static void main(String[] args) { String text = " SomeText SomeText SomeText SomeText SomeText \r\n" + "SomeText SomeText SomeText SomeText SomeText SomeText SomeText SomeText SomeText SomeText.\r\n" + "SomeText SomeText SomeText SomeText SomeText SomeText SomeText SomeText SomeText SomeText.\r\n" + "SomeText SomeText :\r\n" + "SomeText SomeText SomeText SomeText SomeText SomeText (BlockID: 12345,TestCaseID: 12345, 1)"; Pattern p = Pattern.compile("(.+)\\(BlockID: (\\d+),TestCaseID: (\\d+), 1\\)", Pattern.DOTALL); Matcher m = p.matcher(text); while(m.find()) { System.out.println(m.group(1)); System.out.println(m.group(2)); System.out.println(m.group(3)); } } } 将包含foo=bar ./phpunit AllTests 符号后面的第一个文件中的所有元素(如bad_stuff = [] with open('List_1', 'r') as fn: for line in fn: bad_stuff.append(line.split('=')[1].strip()) with open('List_2', 'r') as fn: for line in fn: if line.split(':')[1].strip() not in bad_stuff: print(line) bad_stuff=

然后检查第二个文件,只有在abc符号后面的部分不在列表中hfi

时才会打印