#πŸ”’ How do i remove text from a .txt file?

31 messages Β· Page 1 of 1 (latest)

jaunty isle
#

Hello, I'm new to Python, and I'm working on a to-do list. I'm wondering how to remove a line from a .txt file. I know how to add to a .txt file, but not remove. This is my code:



"""To Do List"""

print("Welcome back .")

user_list = []
with open("user_data.txt", encoding="utf-8") as f:
    user_data = f.read()
user_list.append(user_data)
while True:
    user_input = input("What do you want to do? >>")

    if user_input == "stop":
        break
    elif user_input == "add":
        print(f"Your current To Do List is {user_list}.")
        user_add = input("What will you add to your To Do List? >>")
        user_list.append(user_add)
        with open("user_data.txt", "a", encoding="utf-8") as f:
            f.write(user_add + '/n')
        print(f"Your new To Do List is {user_list}")
    elif user_input == "remove":
        print(f"Your current To Do List is {user_list}.")
        user_remove = input("What will you remove from your To Do List? >>")
        user_list.remove(user_remove)
        print(f"Removed {user_remove} from your To Do List")
sharp sierraBOT
#

@jaunty isle

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.

dreamy umbra
#

Try to format it with ```py and then close it

#

Also take a look at with open πŸ™‚ that would help with your problem

ebon seal
#

ideally, learn how to use sqlite. its a very lightweight database that runs on one single file. no installation required.

vague monolith
quasi venture
#

I'd suggest using a json file, and assign todo with ids, so that cleaning would be easier

vague monolith
# jaunty isle isn't .json for java script?

no, JSON means JavaScript Object Notation, it's a file format that stores data as a text file containing a very limited set of javascript for representing simple javascript objects such as lists, dictionaries, strings, numbers (integers or floats) or booleans, but it can be read or written by almost any programming language and us used for information storage or exchange (like with web APIs and such)

jaunty isle
#

is writing to a json file the same as writing to a .txt file?

vague monolith
#

!d json

sharp sierraBOT
vague monolith
vague monolith
#

the two functions you want is

#

!d json.dump

sharp sierraBOT
#

json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)```
Serialize *obj* as a JSON formatted stream to *fp* (a `.write()`-supporting [file-like object](https://docs.python.org/3/glossary.html#term-file-like-object)) using this [Python-to-JSON conversion table](https://docs.python.org/3/library/json.html#py-to-json-table).

Note

Unlike [`pickle`](https://docs.python.org/3/library/pickle.html#module-pickle) and [`marshal`](https://docs.python.org/3/library/marshal.html#module-marshal), JSON is not a framed protocol, so trying to serialize multiple objects with repeated calls to [`dump()`](https://docs.python.org/3/library/json.html#json.dump) using the same *fp* will result in an invalid JSON file.
vague monolith
#

!d json.load

sharp sierraBOT
#

json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)```
Deserialize *fp* to a Python object using the [JSON-to-Python conversion table](https://docs.python.org/3/library/json.html#json-to-py-table).
vague monolith
# jaunty isle thanks

the other two with an s at the end of the function names is for generating a string or loading data from a string, useful for example when using json with web APIs, but as you are working with files you will probably want the two functions without s at the end since those operate on file handles (what you get after doing your call to open()

vague monolith
# jaunty isle thanks for all the help : )

did you understand how to use the module?
i'm asking since the documentation isn't that great when it comes to examples for the two functions that is without s at the end of the names

jaunty isle
#

i am new after all

vague monolith
# jaunty isle i am new after all

i understand, especially as the documentation didn't have any examples for the very common use case of operating on files, not very beginner friendly i would say
here is a very good and detailed (but also long) article about the python json module (the "Real Python" site is a real gold mine, especially the free parts of the site): https://realpython.com/python-json/

#

@jaunty isle all you really need is to import the module (you typically put imports at the top of your script)

import json
ο»Ώ```then:

* for reading a json file you first need to `open()` the file in read mode (which is the default) and then use `json.load()` to load the data structure into a variable:
```py
with open("user_data.txt", encoding="utf-8") as file:
    user_list = json.load(file)
  • for writing a json file you first need to open() the file in write mode (as soon as you open a file in write mode python truncates the file, which means it empties the file of all its content) and then use json.dump() to write to it:
with open("user_data.txt", "w", encoding="utf-8") as file:
    json.dump(user_list, file)
sharp sierraBOT
#
Python help channel closed for inactivity

This help channel has been closed. 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.