How to Insert Text At Line and Column Position in a File

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

How to add or replace some string at a particular column position in a text file

If your first string change, which means the length, in that case slicing won't work:

Better to use this way:

>>> s.split(' ')
['Roxila', 'almost', 'lost']
>>> p = s.split(' ')
>>> p[0]+'*'+' '.join(p[1:])
'Roxila*almost lost'
>>>

How to get line and column by position in C#?

The simplest and most efficient solution (in terms of memory and performance) which can also be easily adapted to streams rather than strings for large inputs:

    private static (int line, int column, char chr) GetCharFromPosition(string text, int pos)
{
var line = 0;
var col = 0;

for (int i = 0; i <= pos; i++)
{
if (text[i] == '\n')
{
line++;
col = 0;
}
else
{
col++;
}
}

return (line, col, text[pos]);
}

Update after performance comparison. If you are that concerned with performance, and this is run on an in-memory string, this would be the way to go:

private static unsafe (int line, int column, char chr) GetFromPosUnsafe(string text, int pos)
{
var line = 0;
var col = 0;
char c = '\0';
char returnedChar = '\0';
int strLength = text.Length;

fixed (char* p = text)
{
var p1 = p;
for (int i = 0; i < pos; i++)
{
c = *p1++;
if (c == '\n')
{
line++;
col = 0;
}
else
{
col++;
}
returnedChar = c;
}
}

return (line, col, returnedChar);
}

Insert a string in a fixed position in a text file

Add enough spaces to the values (20 in my example), then cut the first [whatever you need] characters (15 in my example):

@echo off
setlocal

FOR /F "delims=; tokens=1-7*" %%a in (mytextfile.txt) do (
if "%%e"=="Unkown" call :format "%%b" "%%c"
)
goto :eof

:format
set "b=%~1 "
set "c=%~2 "
set "b=%b:~0,15%"
set "c=%c:~0,15%"
echo the product %b% %c% doesn't exist>>Unkown_product.txt

Note: the search string is "Unkown" according to your file example (probably a typo, I guess it should be "Unknown")

Append string in a specific place of a text file

Assuming each file has the right tab delimitation (and that's a big assumption given the question quality)

// Get the files
var fileEntries = Directory.GetFiles(path);

// iterate through each file name
foreach (var entry in fileEntries)
{

// Load the File into the lines array
var lines = File.ReadAllLines(entry);

// Iterate over each line
if(lines.Length >1)
{
// Split the lines by tab
var split = lines[1].Split('\t');
// your code should be at array index 1
split[1] = "STRINGTOENTER";
// write the whole line back
lines[1] = string.Join("\t", split);

// write the file
File.WriteAllLines(entry, lines);
}

}

Note : you should probably do this with a CSV parser, this was only for academic purposes and totally untested



Related Topics



Leave a reply



Submit