Inserting Line at Specified Position of a Text File
The best way to make "pseudo-inplace" changes to a file in Python is with the fileinput
module from the standard library:
import fileinput
processing_foo1s = False
for line in fileinput.input('1.txt', inplace=1):
if line.startswith('foo1'):
processing_foo1s = True
else:
if processing_foo1s:
print 'foo bar'
processing_foo1s = False
print line,
You can also specify a backup extension if you want to keep the old version around, but this works in the same vein as your code -- uses .bak
as the backup extension but also removes it once the change has successfully completed.
Besides using the right standard library module, this code uses simpler logic: to insert a "foo bar"
line after every run of lines starting with foo1
, a boolean is all you need (am I inside such a run or not?) and the bool in question can be set unconditionally just based on whether the current line starts that way or not. If the precise logic you desire is slightly different from this one (which is what I deduced from your code), it shouldn't be hard to tweak this code accordingly.
How to insert text at line and column position in a file?
This is possibly a duplicate of below SO thread
Fastest Way to Delete a Line from Large File in Python
In above it's a talk about delete, which is just a manipulation, and yours is more of a modification. So the code would get updated like below
def update(filename, lineno, column, text):
fro = open(filename, "rb")
current_line = 0
while current_line < lineno - 1:
fro.readline()
current_line += 1
seekpoint = fro.tell()
frw = open(filename, "r+b")
frw.seek(seekpoint, 0)
# read the line we want to update
line = fro.readline()
chars = line[0: column-1] + text + line[column-1:]
while chars:
frw.writelines(chars)
chars = fro.readline()
fro.close()
frw.truncate()
frw.close()
if __name__ == "__main__":
update("file.txt", 4, 13, "History ")
In a large file it make sense to not make modification till the lineno where the update needs to happen, Imagine you have file with 10K lines and update needs to happen at 9K, your code will load all 9K
lines of data in memory unnecessarily. The code you have would work still but is not the optimal way of doing it
Add a new line at a specific position in a text file.
This will add the line where you want it. (Make sure you have using System.IO;
and using System.Linq;
added)
public void CreateEntry(string npcName) //npcName = "item1"
{
var fileName = "test.txt";
var endTag = String.Format("[/{0}]", npcName);
var lineToAdd = "//Add a line here in between the specific boundaries";
var txtLines = File.ReadAllLines(fileName).ToList(); //Fill a list with the lines from the txt file.
txtLines.Insert(txtLines.IndexOf(endTag), lineToAdd); //Insert the line you want to add last under the tag 'item1'.
File.WriteAllLines(fileName, txtLines); //Add the lines including the new one.
}
Insert text at a fixed position on each line in a text file
To fix the problem, need few changes.
You might call continue
instead of break
. Modify
if (s == null) break;
to
if (s == null) continue;
Final code snippet should be...
while (reader.Peek() >= 0)
{
string s = reader.ReadLine();
if(string.IsNullOrEmpty(s)) continue;
s = s.Insert(0, "-814590");
writer.WriteLine(s);
}
If you are interested, we can also do this using few Linq
statements.
var formattedLines = File.ReadAllLines("C:/Temp/BOM.txt")
.Where(line => !string.IsNullOrEmpty(line))
.Select(s => s.Insert(12, "-814590")).ToArray();
File.WriteAllLines(@"C:/Temp/xBOM.txt", formattedLines);
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.
Simple way to insert line to particular position in file
awk 'f==1{print last}{last=$0;f=1}END{print "NEW WORD\n"$0}' file
Edit specific line at specific position in Text file in Python
Simply open the existing file and read the lines. Assuming that you want to replace the values that always follow 'addmoney' and 'netmoney', you can locate those lines and use re.sub()
to substitute the values into those lines. Keep in mind that you can't simply overwrite text files in-place, so you store the modified lines and then recreate a new file at the end, like so:
x1 = 123.12
y1 = 123.45
import re
with open('mytextfile.txt', 'r') as f:
lines = f.readlines()
for i, l in enumerate(lines):
if l.startswith('addmoney'):
lines[i] = re.sub(r'[0-9.]+', str(x1), lines[i])
elif l.startswith('netmoney'):
lines[i] = re.sub(r'[0-9.]+', str(y1), lines[i])
out = open('modifiedtextfile.txt', 'w'); out.writelines(lines); out.close()
Related Topics
Sorting a List of Dot-Separated Numbers, Like Software Versions
"Pythonic" Method to Parse a String of Comma-Separated Integers into a List of Integers
Compute a Confidence Interval from Sample Data
How to Add an Integer to Each Element in a List
Prime Number Check Acts Strange
Function Changes List Values and Not Variable Values in Python
Remove Quotes from String in Python
Efficiently Return the Index of the First Value Satisfying Condition in Array
Defining a Discrete Colormap for Imshow in Matplotlib
Do Python for Loops Work by Reference
Is a Python Dictionary an Example of a Hash Table
Reading a Text File and Splitting It into Single Words in Python
Could Pandas Use Column as Index
Pandas "Can Only Compare Identically-Labeled Dataframe Objects" Error
Why Does Str(Float) Return More Digits in Python 3 Than Python 2