How to overwrite a file in Python?

I am trying to overwrite a file. I based my answer on this Read and overwrite 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'))

Output of my current codes:

The file contains cat_descwhen I try to overwrite again as custom. It is being rewritten as customc. Pay attention to cthe end, it should be only custom.

Here is what I am trying to achieve:

  • I write in a file, for example, cat_desc
  • If I want to write again, for example custom, cat_descmust be deleted and replaced with custom.
+5
source share
5 answers

Based on your revised question, maybe something like this will be easier

def auto_sort(request):
    sort_by = request.GET.get('sort_by', None)
    if sort_by:
        temp_path = "{0}/file.txt".format(settings.SITE_ROOT) 
        #Set new_text to whatever you want based on your logic
        new_text = 'custom' 
        f=open(temp_path,'w')
        f.write(new_text)
        f.close();

        handle=open(temp_path,'w+')
        handle.write(sort_by)
        handle.close();

    return HttpResponseRedirect(reverse('envelopes:editor'))
+4
source

New anwser ...

text 4- re.sub. , int

Help on function sub in module re:

sub(pattern, repl, string, count=0, flags=0)
    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a string, backslash escapes in it are processed.  If it is
    a callable, it passed the match object and must return
    a replacement string to be used.

...

,

from os import open

( ) , open ( - ).

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

, , "w +". "r"

+5

:

, . 'cat_desc' 'cat_asc', 'cat_ascc'.

, 'r+', , , seek ing 0 - . -.

, 'w+' ( ) - . , , , .

... . , , , , .

, - " " . , , , . , ; . ... Windows. :

with tempfile.NamedTemporaryFile(delete=False) as outfile:
    with open(inpath) as infile:
        # copy from infile to outfile, changing things as you go
    os.rename(outfile.name, inpath)

, Windows . outfile, , with, , , infile outfile; . , Vista/2008 API Win32.

+5

.

, :

File "/home/cath/src/envelopebudget/envelopebudget/settings/../apps/envelopes/views.py" in auto_sort
  357.         text = re.sub('cat_desc', 'cat_asc', 'custom', text)

re.sub, :

re.sub(pattern, repl, string, count=0, flags=0)

You convey 'cat_desc'how pattern, 'cat_asc'how repl, 'custom'how stringand texthow count. That doesn't make any sense. re.subexpects to countbe an integer, and you gave it a string.

+2
source

Copy and paste the full error back

Try:

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('custom', 'cat_asc', 'cat_desc', text)
        f.close();
        handle=open(temp_path,'w')
        handle.write(sort_by)
        handle.close();
    return HttpResponseRedirect(reverse('envelopes:editor'))
-1
source

All Articles