How to overwrite a file in Python?

2024/9/29 17:30:47

I'm trying to overwrite a file. I based my answer on this Read and overwrite a file in Python

To complete my codes:

<select class="select compact expandable-list check-list" ONCHANGE="location = this.options[this.selectedIndex].value;"><option value="{% url envelopes:auto_sort %}?sort_by=custom">Custom order</option><optgroup label="Category"><option value="{% url envelopes:auto_sort %}?sort_by=cat_asc">Ascending order</option><option value="{% url envelopes:auto_sort %}?sort_by=cat_desc">Descending order</option></optgroup>
</select>def auto_sort(request):sort_by = request.GET.get('sort_by', None)if sort_by:temp_path = "{0}/file.txt".format(settings.SITE_ROOT) f=open(temp_path,'r+')text = f.read()text = re.sub('cat_asc', 'cat_desc', text)f.seek(0)f.write(text)f.truncate()f.close();handle=open(temp_path,'w+')handle.write(sort_by)handle.close();return HttpResponseRedirect(reverse('envelopes:editor'))

The output of my current codes:

The file contains cat_desc when I try rewrite again as custom. It rewrites as customc. Notice the c at the end, it must be custom only.

Here is what I'm trying to achieve:

  1. I write on file, for example, cat_desc
  2. If I want to write again, for example custom, the cat_desc must be removed and replaced with custom.
Answer

New anwser ...

You're passing text as the 4th parameter of re.sub. This is supposed to be an int

Help on function sub in module re:sub(pattern, repl, string, count=0, flags=0)Return the string obtained by replacing the leftmostnon-overlapping occurrences of the pattern in string by thereplacement repl.  repl can be either a string or a callable;if a string, backslash escapes in it are processed.  If it isa callable, it's passed the match object and must returna replacement string to be used.

old answer ...

Perhaps you are doing

from os import open

That is a different (lower level) open, you want to just use the builtin open (you don't need to import anything to use it)

Here is an example of doing it wrong and getting your error message

>>> from os import open
>>> open("some_path", "r+")
Traceback (most recent call last):File "<stdin>", line 1, in <module>
TypeError: an integer is required

Also to overwrite the file, you need to open with "w+". "r" stands for read

https://en.xdnf.cn/q/71183.html

Related Q&A

Is os.popen really deprecated in Python 2.6?

The on-line documentation states that os.popen is now deprecated. All other deprecated functions duly raise a DeprecationWarning. For instance:>>> import os >>> [c.close() for c in os…

Routes with trailing slashes in Pyramid

Lets say I have a route /foo/bar/baz. I would also like to have another view corresponding to /foo or /foo/. But I dont want to systematically append trailing slashes for other routes, only for /foo a…

understanding item for item in list_a if ... PYTHON

Ive seen the following code many times, and I know its the solution to my problems, but Im really struggling to understand HOW it works. The code in particular is:item for item in list_a if item not in…

Django redirect to custom URL

From my Django app, how to I redirect a user to somescheme://someurl.com?To give you some context in case it helps, I have a working oauth2 server written in Python/Django and I need to allow users to…

Python embedding with threads -- avoiding deadlocks?

Is there any way to embed python, allow callbacks from python to C++, allowing the Pythhon code to spawn threads, and avoiding deadlocks?The problem is this:To call into Python, I need to hold the GIL…

RuntimeError: Event loop is closed when using pytest-asyncio to test FastAPI routes

I received the errorRuntimeError: Event loop is closedeach time I try to make more than one async call inside my test. I already tried to use all other suggestions from other Stack Overflow posts to re…

Adjust threshold cros_val_score sklearn

There is a way to set the threshold cross_val_score sklearn?Ive trained a model, then I adjust the threshold to 0.22. The model in the following below :# Try with Threshold pred_proba = LGBM_Model.pre…

Efficiently insert multiple elements in a list (or another data structure) keeping their order

I have a list of items that should be inserted in a list-like data structure one after the other, and I have the indexes at which each item should be inserted. For example: items = [itemX, itemY, itemZ…

matplotlib versions =3 does not include a find()

I am running a very simple Python script: from tftb.generators import amgauss, fmlinI get this error: C:\Users\Anaconda3\envs\tf_gpu\lib\site-packages\tftb-0.0.1-py3.6.egg\tftb\processing\affine.py in …

How to fix Field defines a relation with the model auth.User, which has been swapped out

I am trying to change my user model to a custom one. I do not mind dropping my database and just using a new one, but when I try it to run makemigrations i get this errorbookings.Session.session_client…