2

I want to add a new string to the previous one like, I have some text in the file,

1
2
3

Now I want to add a new string behind the last sentence,not a new line

1
2
3hello

and the code like that,

file_convt = open("test.txt", "w")
for i in range(0, 3):
    file_convt.write(str(i) + "\n")
file_convt.write("hello")
file_convt.close()

The loop function is complex actually and I cannot change it, is there some better way can add a new line behind the last sentence? I only know,

with open(filepath, "w") as fp:
    for line in lines:
        print(line + "#", file=fp)

However, my file is large and I am afraid to read it all in everytime..

4daJKong
  • 1,825
  • 9
  • 21

2 Answers2

2

Using the end argument to print to avoid a newline being printed. We only prepend a newline after the first line is printed.

lines = ['1', '2', '3']
prepend = ''

for line in lines:
    print(f"{prepend}{line}", end='')
    prepend = "\n"

print("hello", end='')
Chris
  • 26,361
  • 5
  • 21
  • 42
0

seek() method In Python,

seek() function is used to change the position of the File Handle to a given specific position. File handle is like a cursor, which defines from where the data has to be read or written in the file.

Please visit GFG site for more information regarding seek method.

When I tried to move the cursor to the end of the text file I got exception UnsupportedOperation: can't do nonzero end-relative seeks so I have to seek only from the beggining of file.

text files do not have a 1-to-1 correspondence between encoded bytes and the characters they represent, so seek can't tell where to jump to in the file to move by a certain number of characters.

above quote from this site of stack overflow.

This might not be complete solution but it works and hope it might give you some help so you could use it to solve the problem.

os.stat is used to get the file size. After knowing to file size we can use seek method to go to appropriate position can modify the file efficiently.

import sys,random, os
file_convt = open("test.txt", "w")
for i in range(0, 3):
    file_convt.write(str(i+1) + "\n")
file_convt.close()

stats = os.stat('test.txt')
#print(stats.st_size)

with open("test.txt", "r+")as f:
    f.seek(stats.st_size-1,0) #now our cursor is after 3 and here we can write hello
    f.write("hello\n")

Output:

$ cat test.txt 
1
2
3hello
Udesh
  • 2,415
  • 2
  • 22
  • 32