Prepend a line to an existing file in Python
Python makes a lot of things easy and contains libraries and wrappers for a lot of common operations, but the goal is not to hide fundamental truths.
The fundamental truth you are encountering here is that you generally can't prepend data to an existing flat structure without rewriting the entire structure. This is true regardless of language.
There are ways to save a filehandle or make your code less readable, many of which are provided in other answers, but none change the fundamental operation: You must read in the existing file, then write out the data you want to prepend, followed by the existing data you read in.
By all means save yourself the filehandle, but don't go looking to pack this operation into as few lines of code as possible. In fact, never go looking for the fewest lines of code -- that's obfuscation, not programming.
Prepend line to beginning of a file
In modes 'a'
or 'a+'
, any writing is done at the end of the file, even if at the current moment when the write()
function is triggered the file's pointer is not at the end of the file: the pointer is moved to the end of file before any writing. You can do what you want in two manners.
1st way, can be used if there are no issues to load the file into memory:
def line_prepender(filename, line):
with open(filename, 'r+') as f:
content = f.read()
f.seek(0, 0)
f.write(line.rstrip('\r\n') + '\n' + content)
2nd way:
def line_pre_adder(filename, line_to_prepend):
f = fileinput.input(filename, inplace=1)
for xline in f:
if f.isfirstline():
print line_to_prepend.rstrip('\r\n') + '\n' + xline,
else:
print xline,
I don't know how this method works under the hood and if it can be employed on big big file. The argument 1 passed to input is what allows to rewrite a line in place; the following lines must be moved forwards or backwards in order that the inplace operation takes place, but I don't know the mechanism
How to insert a new line before the first line in a file using python?
you can use fileinput
>>> import fileinput
>>> for linenum,line in enumerate( fileinput.FileInput("file",inplace=1) ):
... if linenum==0 :
... print "new line"
... print line.rstrip()
... else:
... print line.rstrip()
...
how to add lines to existing file using python
If you want to append to the file, open it with 'a'
. If you want to seek through the file to find the place where you should insert the line, use 'r+'
. (docs)
How can I add a new line of text at top of a file?
You can't do what you're trying to do. Seeking to the beginning of a file and doing a write will overwrite from that position, not append.
The only way to add a line in the middle (or beginning) of a file is to write out a new file with the data inserted where you want it to.
Append text to a Text file without replacing it Python
When you write
to a file it always effectively overwrites the bytes inside the file stream. What you might want to do instead, is read the file first, and write the necessary parts, and then write your original contents back:
with open(filename,'r+',encoding="UTF-8") as file:
data = file.read()
file.write('test\n')
file.write(data)
This should be all you need. Remove the f = open(filename)
and file_contents = f.read()
lines, because you are opening the same file twice.
Insert line at middle of file with Python?
This is a way of doing the trick.
with open("path_to_file", "r") as f:
contents = f.readlines()
contents.insert(index, value)
with open("path_to_file", "w") as f:
contents = "".join(contents)
f.write(contents)
index
and value
are the line and value of your choice, lines starting from 0.
Append String to each line of .txt file in python?
You can read the lines and put them in a list. Then you open the same file with write mode and write each line with the string you want to append.
filepath = "hole.txt"
with open(filepath) as fp:
lines = fp.read().splitlines()
with open(filepath, "w") as fp:
for line in lines:
print(line + "#", file=fp)
Related Topics
Validate Ssl Certificates with Python
How to Set Class Attributes from Variable Arguments (Kwargs) in Python
Python: How to Get Stdout After Running Os.System
Django Db Settings 'Improperly Configured' Error
How to Use Multiprocessing Queue in Python
Python: Pandas Series - Why Use Loc
Custom Filter in Django Admin on Django 1.3 or Below
How to Retrieve Items from a Dictionary in the Order That They'Re Inserted
How Does Condensed Distance Matrix Work? (Pdist)
Pip Installing in Global Site-Packages Instead of Virtualenv
Spark Dataframe Distinguish Columns with Duplicated Name
Python Pip Install Module Is Not Found. How to Link Python to Pip Location
Python Enum, When and Where to Use
Remove File After Flask Serves It