Python我如何检查文件的每一行,看看它是否包含列表中的某个项,以及它是否确实从fi中删除了该行

2024-04-29 01:45:55 发布

您现在位置:Python中文网/ 问答频道 /正文

Possible Duplicate:
Compare two different files line by line and write the difference in third file - Python

我脑子里的逻辑是这样的。。。 对于导入文件中的行,请检查它是否包含现有用户字符串列表中的任何项如果它包含该列表中的任何项,然后删除该文件的行。

filenew = open('new-user', 'r')
filexist = open('existing-user', 'r')
fileresult = open('result-file', 'r+')
xlines = filexist.readlines()
newlines = filenew.readlines()
for item in newlines:
    if item contains an item from xlines
        break
    else fileresult.write(item)
filenew.close()
filexist.close()
fileresult.close()

我知道这些代码都是伪造的,但也许你可以给我指出正确的方向。

谢谢!

编辑----

以下是我现有用户文件中的内容示例….

allyson.knanishu
amy.curtiss
amy.hunter
amy.schelker
andrea.vallejo
angel.bender
angie.loebach

以下是我的新用户文件中的内容示例….

aimee.neece,aimee,neece,aimee.neece@faculty.asdf.org,aimee neece,aimee neece,"CN=aimee neece,OU=Imported,dc=Faculty,dc=asdf,dc=org"
alexis.andrews,alexis,andrews,alexis.andrews@faculty.asdf.org,alexis andrews,alexis andrews,"CN=alexis andrews,OU=Imported,dc=Faculty,dc=asdf,dc=org"
alice.lee,alice,lee,alice.lee@faculty.asdf.org,alice lee,alice lee,"CN=alice lee,OU=Imported,dc=Faculty,dc=asdf,dc=org"
allyson.knanishu,allyson,knanishu,allyson.knanishu@faculty.asdf.org,allyson knanishu,allyson knanishu,"CN=allyson knanishu,OU=Imported,dc=Faculty,dc=asdf,dc=org"

来自@mikebabcock的新代码。。。谢谢。

outfile = file("result-file.txt", "w")
lines_to_check_for = [ parser(line) for line in file("existing-user.txt", "r") ]
for line in file("new-user.txt", "r"):
    if not parser(line) in lines_to_check_for:
        outfile.write(line)

为分析器添加了导入语句。。。我收到以下错误。。。

C:\temp\ad-import\test-files>python new-script.py
Traceback (most recent call last):
  File "new-script.py", line 7, in <module>
    lines_to_check_for = [ parser(line) for line in file("existing-user.txt", "r
     ") ]
  TypeError: 'module' object is not callable

谢谢!


Tags: inorgforlinedcfilealiceasdf