Let's say I have a text file full of random lines. How can I keep a specific line and delete the others from this file, using Python? The script should search for all .txt files from a directory/and sub directory.
Asked
Active
Viewed 129 times
-1
-
Not quite, but close – MoonMist Feb 05 '19 at 00:45
1 Answers
0
Firstly, to search for all .txt
files, you can use this:
import glob, os
os.chdir("/mydir")
for filePath in glob.glob("*.txt"):
...
Sourced from here
Secondly, to look through a file and find the line you want, use:
myfile = open(filePath, "r")
And look to see if your desired line is in the file.
if desiredLine in myfile:
...
Then you can close the file and reopen it in write mode.
myfile.close()
myfile = open(filePath, "w")
Then all you have to do is write the line you wanted to keep.
myfile.write(desiredLine)
Then close the file again
myfile.close()
Sourced from here
The final script ends up like this:
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()
Note, if your line doesn't exist in the file you're checking, it is left as is.
Hope this helps you

MoonMist
- 1,232
- 6
- 22
-
`if desiredLine in file:` would short-circuit as soon as the line was found without having to read the whole file into memory (and would only require peak memory proportionate to the longest line, not proportionate to file size, which is a good idea if files can be huge). Also, you could open the file just once in `r+` mode, if you find the line, `seek` to the beginning, `write` the line, then `truncate` the file, which avoids opening/closing the file twice. Lastly, `file.open(filePath, "w")` isn't legal; you probably meant `file = open(filePath, "w")` or `with open(filePath, "w") as file:`. – ShadowRanger Feb 05 '19 at 00:56
-
-
I don't understand what you're saying first though. The statement is `if desiredLine in file.readlines():` not `if desiredLine in file:` – MoonMist Feb 05 '19 at 01:00
-
I was saying `if desiredLine in file:` would accomplish the same goal as `if desiredLine in file.readlines():` more efficiently. `if desiredLine in file:` would lazily consume lines from the file until it found a match (and immediately returned `True`) or exhausted the file (and returned `False`). – ShadowRanger Feb 05 '19 at 01:02
-