Reputation: 5444
I have got a file in python with filenames. I want to delete some lines and some substirng of the filename using python code. My file format is the above:
img/1.jpg
img/10.jpg
img/100.jpg 0 143 84 227
...
I want to delete the img/substring from all the file and the lines where the coordinates are missing. For the second task I did the following:
for con in content:
if ".jpg\n" in con:
content.remove(con)
for con in content:
print con
However content didn't change.
Upvotes: 0
Views: 448
Reputation: 12077
You're attempting to modify the list content
while iterating over it. This will very quickly bite you in the knees.
Instead, in python you generate a new list:
>>> content = [fn for fn in content if not fn.endswith(".jpg\n")]
>>>
After this you can overwrite the file you read from with the contents from... contents
. The above example assumes there is no whitespace to accomodate for in between the filename and the newline.
Upvotes: 2
Reputation: 5514
The error in your current method is because you are iterating through each line by letter, for l in somestring:
will go letter by letter. Obviously, a ".jpg\n"
won't be in a single letter, so you never hit content.remove(con)
.
I would suggest a slightly different approach:
with open("fileofdata.txt", 'r') as f:
content = [line for line in f.readlines() if len(line.split()) > 1]
Using len(line.split())
is more robust than line.endswith()
because it allows for withspace between .jpg
and \n
.
Upvotes: 1