0

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.

3
  • Is content supposed to be each line in the file? Commented Nov 11, 2014 at 14:03
  • 4
    You really don't want to modify the content list while iterating over it with a for loop either. Commented Nov 11, 2014 at 14:04
  • Yes and every line is a filename for example img/1.jpg Commented Nov 11, 2014 at 14:04

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.