How do I modify the last line of a file?
The last line of my file is:
How can I modify that line so that it reads:
Note: I don't want to write a new line. I want to take the same line and put new values after
I'm new at python. I'm having a lot of trouble manipulating files and for me every example I look at seems difficult.
Asked by: Haris633 | Posted: 01-10-2021
The below code sample reads the file into a list of "lines", edits the last line, then writes it back out to the file:
#!/usr/bin/python MYFILE="file.txt" # read the file into a list of lines lines = open(MYFILE, 'r').readlines() # now edit the last line of the list of lines new_last_line = (lines[-1].rstrip() + ",90,100,50") lines[-1] = new_last_line # now write the modified list back out to the file open(MYFILE, 'w').writelines(lines)
If the file is very large then this approach will not work well, because this reads all the file lines into memory each time and writes them back out to the file, which is very inefficient. For a small file however this will work fine.Answered by: Ned272 | Posted: 02-11-2021
Unless the file is huge, you'll probably find it easier to read the entire file into a data structure (which might just be a list of lines), and then modify the data structure in memory, and finally write it back to the file.
On the other hand maybe your file is really huge - multiple GBs at least. In which case: the last line is probably terminated with a new line character, if you seek to that position you can overwrite it with the new text at the end of the last line.
f = open("foo.file", "wb") f.seek(-len(os.linesep), os.SEEK_END) f.write("new text at end of last line" + os.linesep) f.close()
(Modulo line endings on different platforms)Answered by: Blake866 | Posted: 02-11-2021
Don't work with files directly, make a data structure that fits your needs in form of a class and make read from/write to file methods.Answered by: Adrian344 | Posted: 02-11-2021
I recently wrote a script to do something very similar to this. It would traverse a project, find all module dependencies and add any missing import statements. I won't clutter this post up with the entire script, but I'll show how I went about modifying my files.
import os from mmap import mmap def insert_import(filename, text): if len(text) < 1: return f = open(filename, 'r+') m = mmap(f.fileno(), os.path.getsize(filename)) origSize = m.size() m.resize(origSize + len(text)) pos = 0 while True: l = m.readline() if l.startswith(('import', 'from')): continue else: pos = m.tell() - len(l) break m[pos+len(text):] = m[pos:origSize] m[pos:pos+len(text)] = text m.close() f.close()
Summary: This snippet takes a filename and a blob of text to insert. It finds the last import statement already present, and sticks the text in at that location.
The part I suggest paying most attention to is the use of mmap. It lets you work with files in the same manner you may work with a string. Very handy.Answered by: Darcy603 | Posted: 02-11-2021
python - Modify a DBF file
I want to modify one column in a .dpf file using Python with this library http://pythonhosted.org/dbf/. When I want to print out some column, it works just fine. But when I am trying to modify a column, I get error unable to modify fields individually except in with or Process() My code:
Bash or Python or Awk to match and modify files
I have a set of 10000 files c1.dat ... c10000.dat. Each of these files contains a line which starts with @ and contains a string with spaces specific for this file, lije c37 7.379 6.23. I have another set of 10000 files kind of determined_cXXX_send.dat (where XXX goes from 1 to 10000). Each of these files has only one line. Each line is of thsis type: _1 1 3456.000000 -21 0 -98.112830 -20.326192
python - How hard is it to modify the Django Models?
I am doing geolocation, and Django does not have a PointField. So, I am forced to writing in RAW SQL. GeoDjango, the Django library, does not support the following query for MYSQL databases (can someone verify that for me?) cursor.execute("SELECT id FROM l_tag WHERE\ (GLength(LineStringFromWKB(LineString(asbinary(utm),asbinary(PointFromWKB(point(%s, %s)))))) < %s + accuracy + %s)\
python - Modify Django admin app index
I want to change the app index page so I add help text to the models themselves, e.g. under each model I want to add help text. I know that I should override AdminSite.app_index. What is the best way to do this?
python - Modify Django Forms
I've recently been developing on the django platform and have stumbled upon Django Forms (forms.Form/forms.ModelForm) as ways of creating <form> html. Now, this is brilliant for quick stuff but what I'm trying to do is a little bit more complicated. Consider a DateField - my current form has fields for day, month and year and constructs a python date object ...
python - modify text file
I need to modify all files that has a ".txt" extension within a directory in the following way: remove all text lines beginning with the line that starts with "xxx" and the line that ends with "xxx", inclusive. I know how to do this in Java or C++, but can someone show me a simple script that can get this done? Thanks!
python modify item in list, save back in list
I have a hunch that I need to access an item in a list (of strings), modify that item (as a string), and put it back in the list in the same index I'm having difficulty getting an item back into the same index for item in list: if "foo" in item: item = replace_all(item, replaceDictionary) list[item] = item print item now I get an error T...
python - How can I modify this regex to match all three cases?
I want to test if a method appears in a header file. These are the three cases I have: void aMethod(params ...) //void aMethod(params // void aMethod(params ^ can have any number of spaces here Here's what I have so far: re.search("(?<!\/\/)\s*void aMethod",buffer) Buf this will only match the first case, and the second. How could I tweak it to have i...
Python C API: Modify search path
How can I add a speciific directory to the search path using the C API? And a related question: will the changes be local to the application, or is the search path global?
python - Modify the width of a tab in a format string
Is it possible to redefine the space width of a tab when printing a \t character in python?
python - How can I modify the STDOUT?
I'm currently writing a very simple terminal tool and I want to implement the following behavior. The terminal should display: Downloading "Something" ... And after I have completed the download, I want to replace that line with: Downloading "Something" [Done] I have seen this done o create the following animation: [-] [\] [|] [/]
How can I use a DLL file from Python?
What is the easiest way to use a DLL file from within Python? Specifically, how can this be done without writing any additional wrapper C++ code to expose the functionality to Python? Native Python functionality is strongly preferred over using a third-party library.
python - PubSub lib for c#
Is there a c# library which provides similar functionality to the Python PubSub library? I think it's kind of an Observer Pattern which allows me to subscribe for messages of a given topic instead of using events.
python - What is the best way to copy a list?
This question already has answers here:
python - Possible Google Riddle?
My friend was given this free google website optimizer tshirt and came to me to try and figure out what the front logo meant. t-shirt So, I have a couple of guesses as to what it means, but I was just wondering if there is something more. My first guess is that eac...
How do you check whether a python method is bound or not?
Given a reference to a method, is there a way to check whether the method is bound to an object or not? Can you also access the instance that it's bound to?
ssh - How to scp in Python?
What's the most pythonic way to scp a file in Python? The only route I'm aware of is os.system('scp "%s" "%s:%s"' % (localfile, remotehost, remotefile) ) which is a hack, and which doesn't work outside Linux-like systems, and which needs help from the Pexpect module to avoid password prompts unless you already have passwordless SSH set up to the remote host. I'm aware of Twisted'...
python - How do I create a new signal in pygtk
I've created a python object, but I want to send signals on it. I made it inherit from gobject.GObject, but there doesn't seem to be any way to create a new signal on my object.
python - What do I need to import to gain access to my models?
I'd like to run a script to populate my database. I'd like to access it through the Django database API. The only problem is that I don't know what I would need to import to gain access to this. How can this be achieved?
python - How do I edit and delete data in Django?
I am using django 1.0 and I have created my models using the example in the Django book. I am able to perform the basic function of adding data; now I need a way of retrieving that data, loading it into a form (change_form?! or something), EDIT it and save it back to the DB. Secondly how do I DELETE the data that's in the DB? i.e. search, select and then delete! Please show me an example of the code ...