#πŸ”’ Can Python delete specific lines in a file, or a parse and "rewrite" needed?

12 messages Β· Page 1 of 1 (latest)

trail willow
#

Hello. I am relatively new to Python, so please bear with me. If my question is unclear, let me know. Thank you in advance.

I have a series of short files with a two unnecessary lines in them: ---, and old_path: /path/here/. There are multiple instances of --- in the files - I only want to delete the instance of it above old_path. Alternatively, I can delete the --- under the path under old_path... The idea is to delete one instance of the ---, and the old_path line. The rest of the content should remain as-is.

Example content:

_model: redirect
---
old_path: /path/here/
---
new_path: /path/to/directory/here/
---
_discoverable: no

Can Python delete these specific lines? Or is this a situation where I need to parse the file, redo the content without those lines in it, and rewrite the file with the new content?

lusty pewterBOT
#

@trail willow

Python help channel opened

Remember to:

  • Ask your Python question, not if you can ask or if there's an expert who can help.
  • Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
  • Explain what you expect to happen and what actually happens.

:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.

trail willow
#

Can Python delete specific lines in a file, or is a parse and "rewrite" needed?

strange tapir
#

generally speaking you have to rewrite the entire file if you want to make any changes to the middle of it

if it's reasonably small, you can just read into memory, manipulate as a string, then write back to the file

trail willow
#

Ooh. Ok. The example content is the whole file. So I assume that's small enough to read into memory.

strange tapir
#

yeah "too large" would be multiple GBs, or at least hundreds of MBs

trail willow
#

Ah alright

strange tapir
#

you can probably just start = string.index("old_path") end = string.index("---", start) then take slices string[:start] + string[end:] or something like that

trail willow
#

Do slices require character numbers? Or .... oh.... I see what you're saying.

#

I think I get it! Thank you!

lusty pewterBOT
#
Python help channel closed

This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.