python常见笔试题汇总

1.有两个文件 a.txt b.txt:

a文件内容包含内容类似: b文件内容包含内容类似:

a.txt              b.txt

test              aaa

abc              bbb

testabc             abc

                testabc

用pyhton语言完成文件操作,并将文件中拥有相同内容的行输出到一个新建的文件c.txt 中

解法一:

考察知识点:1)文件读写;2)split()字符串分割函数,返回值为一个数组;3)join() list转字符串函数,返回一个字符串

with open('a.txt', 'r') as f:
    a = f.read()
    a1 = a.split("\n")

with open('b.txt', 'r') as f:
    b = f.read()
    b1 = b.split("\n")
    print(b.split("\n"))

c = []
for i in range(len(a1)):
    if str(a1[i]) in b1:
        c.append(a1[i])
with open("c.txt", 'w') as f:
            f.write('\n'.join(c))

解法二: 

with open("a.txt")as f1:
    lines1 = set(f1.readlines())
with open("b.txt")as f2:
    lines2 = set(f2.readlines())
lines = lines1 & lines2
for line in lines:
    with open("c.txt", "a") as f:
        f.write(line)