From 11:00 PM CDT Friday, Nov 8 - 2:30 PM CDT Saturday, Nov 9, ni.com will undergo system upgrades that may result in temporary service interruption.

We appreciate your patience as we improve our online experience.

LabVIEW

cancel
Showing results for 
Search instead for 
Did you mean: 

How to replace a line in a csv file

Hi everyone,
 
What i need to do is to write into a csv file, line by line. When I'm in the line #1000, I need to go back to line #1 and replace the old line by a new line.
 
I only found a way to do this but I don't think it's a good way.
I read the actual file, I put it in an array (with spreadsheet string to array), I replace the text in the specific index of the array, I delete the old file and I convert the array to a spreadsheet string and then write it in a new file. It's strange but it works. Is there any other (smarter) way to do this?
 
Thank you
 
Stéphanie
0 Kudos
Message 1 of 6
(4,155 Views)
IF the text that you're replacing is the same exact length as the text that you're replacing it with, then you can change the file position while writing and write out the new text, then change the file position to the end of the file to continue writing. If the text is different then you cannot do this, and you essentially have to create the new file in memory and then write it out to file, as you're doing. However, you do not need to delete the old file, as you can use the file I/O functions to overwrite the file in one step.
0 Kudos
Message 2 of 6
(4,137 Views)

Hi

Thank you for your answer.

The text is not the same length as the other text, so that's why I didn't use the "Get position.vi".
The overwrite function looks like a good idea, but I don't find it. Do you know the exact name of it?
 
Thank you again
 
 
Stéphanie
0 Kudos
Message 3 of 6
(4,107 Views)


@Peachy wrote:
The overwrite function looks like a good idea, but I don't find it. Do you know the exact name of it?

Just write at a given postion and the existing data at that file location will be overwritten. No special function needed.

For this to work well, you should consider using fixed length lines.

0 Kudos
Message 4 of 6
(4,100 Views)

Thanx for your idea.

Unfortunatly, I can't have the same length on every line. I don't know what's going to be witten in the text.

 

Stephanie

0 Kudos
Message 5 of 6
(4,095 Views)


@Peachy wrote:
Unfortunatly, I can't have the same length on every line. I don't know what's going to be witten in the text.


Unfortunately, in this case you cannot really do what you want. Whenever you replace a line, all bytes to the right need to be shifted up or down to account for the change in length. A file is just a long sequence of bytes and a line break is just the presence of a newline character. There is no concept of "lines" per se.

0 Kudos
Message 6 of 6
(4,090 Views)