使用Python来删除一个文本文件行[复制]

问题描述 投票:-1回答:1

这个问题已经在这里有一个答案:

比方说,我有一个文本文件的完整的随机线。我怎样才能保持一个特定的线路,并删除其他从这个文件中,使用Python?该脚本应搜索从目录/和子目录中的所有.txt文件。

python python-2.7 file-io
1个回答
0
投票

首先,搜索所有.txt文件,你可以这样做:

import glob, os
os.chdir("/mydir")
for filePath in glob.glob("*.txt"):
    ...

here来源

其次,要通过文件看看,找到你想要的路线,使用方法:

 myfile = open(filePath, "r")

而看看如果你想要行的文件中。

if desiredLine in myfile:
    ...

然后你就可以关闭该文件,并在写模式重新打开。

myfile.close()
myfile = open(filePath, "w")

然后,所有你需要做的就是写你想保持一致。

myfile.write(desiredLine)

然后再次关闭文件

myfile.close()

here来源

最后脚本结束这样的:

import glob, os
os.chdir("/mydir")
for filePath in glob.glob("*.txt"):
    myfile = open(filePath, "r")
    if desiredLine in myfile:
        myfile.close()
        myfile = open(filePath, "w")
        myfile.write(desiredLine)
    myfile.close()

请注意,如果你的行不,你正在检查的文件存在,则保持原样。

希望这可以帮助你

© www.soinside.com 2019 - 2024. All rights reserved.