Append text to the last line of file with python

2024/9/22 18:26:07

First, I use echo 'hello,' >> a.txt to create a new file with one line looks like that. And I know \n is at the last of the line.

enter image description here

Then I get some data from python, for example "world", I wish to append "world" at the first line, so I use the python code below:

f = open('a.txt','a')
f.write("world\n")
f.flush()
f.close()

And, here is the result. I know the start point for python to write is at the next line, but I don't know how to fix it.

enter image description here

Answer

To overwrite the previous file contents you need to open it in 'r+' mode, as explained in this table. And to be able to seek to arbitrary positions in the file you need to open it in binary mode. Here's a short demo.

qtest.py

with open('a.txt', 'rb+') as f:# Move pointer to the last char of the filef.seek(-1, 2)f.write(' world!\n'.encode())

test

$ echo 'hello,' >a.txt
$ hd a.txt 
00000000  68 65 6c 6c 6f 2c 0a                              |hello,.|
00000007
$ ./qtest.py
$ hd a.txt 
00000000  68 65 6c 6c 6f 2c 20 77  6f 72 6c 64 21 0a        |hello, world!.|
0000000e
https://en.xdnf.cn/q/119107.html

Related Q&A

Python Caesar Cipher [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 2…

Indent Expected? [duplicate]

This question already has answers here:Im getting an IndentationError (or a TabError). How do I fix it?(6 answers)Closed 7 months ago.Im sort of new to python and working on a small text adventure its…

Convert QueryDict to key-value pair dictionary

I have a QueryDict that I get from request.POST in this format: <QueryDict: {name: [John], urls: [google.com/\r\nbing.com/\r\naskjeeves.com/], user_email: [[email protected]]}>Why are the values …

How to test items with each other in 2 dimensional list?

We have a 2 dimensional list (for this example we have it populated with unique 6 nodes and 3 masks)myList = [[node1, mask1], [node2, mask1], [node3, mask1], [node4, mask2], [node5, mask2], [node6, mas…

InsecureRequestWarning + MarkupResemblesLocatorWarning:

Id like to scrape a site for my office work. I am learning each day. I need your support guys. Here is the Code: url = https://www.eprocure.gov.bd/partner/ViewTenderPaymentDetails.jsp?payId=33767442&a…

Fetching images from URL and saving on server and/or Table (ImageField)

Im not seeing much documentation on this. Im trying to get an image uploaded onto server from a URL. Ideally Id like to make things simple but Im in two minds as to whether using an ImageField is the b…

Comparing list with a list of lists

I have a list string_array = [1, 2, 3, 4, 5, 6] and a list of lists multi_list = [[1, 2], [2, 3], [2, 4], [4, 5], [5, 6]]The first element of each sub-list in multi_list will have an associated entry …

Cannot save data to database Python

I have a table called category TABLES["category"] = ("""CREATE TABLE category (category_id INTEGER NOT NULL AUTO_INCREMENT,category_name VARCHAR(120) NOT NULL,PRIMARY KEY (cate…

How to generate a permutation of list of lists in python

I have a list of lists say[[2, 4, 6], [2, 6, 10], [2, 12, 22], [4, 6, 8], [4, 8, 12], [6, 8, 10], [8, 10, 12], [8, 15, 22], [10, 11, 12]]How do I generate a combination of the lists for a given length?…

Issue sending file via Discord bot (Python)

if message.content.upper().startswith("!HEADPATS"):time.sleep(1)with open(tenor.gif, rb) as picture:await client.send_file(channel, picture)Ive got my discord bot up and running (everythings …