Insert a line into the middle of a text file in Python
If you want to write in the middle of the file use
fileinput
module.
import fileinput
for line in fileinput.input("C:\\Users\\Administrator\\Desktop\\new.txt",inplace=True):
print "something", #print("something", end ="") for python 3
remember whatever you print that will go in the file.So you have to read and print every line and modify whichever you want to replace.Also use
print "asd",...the
,at the end is important as It will prevent
printfrom putting a newline there.
How do I append a string to a line in the middle of a file using python?
You can use re.sub
. After reading the file with f.read()
you can use see f.seek(0)
to rewind to the beginning and use f.write()
to write your new content (you need to open the file with r+
flag):
Content of the file.txt
:
Line1
Line2
Line3
Line4
Script:
import re
SubjectName = 'Line3'
with open('file.txt', 'r+') as f:
s = f.read()
new_s = re.sub(r'^(.*{}.*)$'.format(re.escape(SubjectName)), lambda g: g.group(0) + ',--processed', s, flags=re.MULTILINE)
f.seek(0)
f.write(new_s)
Afer running the file.txt
contains:
Line1
Line2
Line3,--processed
Line4
Can you write to the middle of a file in python?
I think what you can do is to substitute already existing characters with the same amount of other characters you want. You can open a file, locate the starting point, and start writing. But you will overwrite all the following bytes if you use f.write()
. If you want to "insert" something inbetween, you have to read and rewrite all the following content of the file.
Overwrite:
with open('text.txt', 'w') as f:
f.write("0123456789")
# now the file 'text.txt' has "0123456789"
with open('text.txt', 'r+b') as f:
f.seek(-4, 2)
f.write(b'a')
# now the file 'text.txt' has "012345a789"
Insert:
with open('text.txt', 'w') as f:
f.write("0123456789")
# now the file 'text.txt' has "0123456789"
with open('text.txt', 'r+b') as f:
f.seek(-4, 2)
the_rest = f.read()
f.seek(-4, 2)
f.write(b'a')
f.write(the_rest)
# now the file 'text.txt' has "012345a6789"
Insert contents of a file in middle of another file with Python?
Why do you think it is any different from this probable SO question you are referring to?
Its just that instead of inserting a line, you need to read your inputfile.txt
into a variable as shown here
and insert that into the file, instead of the value
as clearly shown in the question. (links provided above)
Inserting a file's text into another file at a specific line
Simple but somewhat memory-intensive:
# insert contents of "/test1.txt" into "/test2.txt" at line 20
with open("/test1.txt", "r") as f1:
t1 = f1.readlines()
with open("/test2.txt", "r") as f2:
t2 = f2.readlines()
t2.insert(20, t1)
with open("/test2.txt", "w") as f2:
f2.writelines(t2)
Minimizes memory usage and disk writes, but is a little more complex :
# insert contents of "/test1.txt" into "/test2.txt" at line 20
with open("/test2.txt", "rw+") as f2:
for x in range(20):
f2.readline() # skip past early lines
pos = f2.tell() # remember insertion position
f2_remainder = f2.read() # cache the rest of f2
f2.seek(pos)
with open("/test1.txt", "r") as f1:
f2.write(f1.read())
f2.write(f2_remainder)
I haven't tested either of these, but they should get you most of the way there.
Related Topics
Generate 'N' Unique Random Numbers Within a Range
How to Install Python3 Version of Package via Pip on Ubuntu
What Does the 'U' Symbol Mean in Front of String Values
Execute Code When Django Starts Once Only
Main() Function Doesn't Run When Running Script
How to Read a Text File into a List or an Array with Python
How to Delete Rows from a Pandas Dataframe Based on a Conditional Expression
How to Time a Code Segment for Testing Performance with Pythons Timeit
Getting Distance Between Two Points Based on Latitude/Longitude
Understanding Nested List Comprehension
Error Unicodedecodeerror: 'Utf-8' Codec Can't Decode Byte 0Xff in Position 0: Invalid Start Byte
How to Extract the N-Th Elements from a List of Tuples
Python: Why Is Functools.Partial Necessary
How to Create a Copy of an Object in Python