Read/write line from textfile

Hello,

is it possible to read/edit a line in a textfile stored on the SD-Card?

For example:
I want to read line 7 in textfile "test.txt".
After checking the read data, I want to replace the data in line 7 with "xxx".

If searched for a solution, but I was not able to find anything about that.

Thanks
Waelder

The first issue is that you'd like the YUN to manipulate text. That's like trying to play Crysis on a calculator XD. The next issue is that when writing to files, the file pointer is automatically placed at the EOF (unless specified otherwise) meaning some special manipulation is required to insert text in between lines of a file rather than at the end. I personally use python to do chores like this because of it's rich text manipulation modules. If, however, you aren't familiar with python, you may have to do this task manually or find a different solution.

Here is a push in the right direction:

with open("path/to/test.txt", 'w+') as fout:
    for line in fout:
        if 'line 7' in line:
            fout.write("xxx")
fout.close()

if you just want to read a specific line with python:

import linecache

line = linecache.getline("path/to/test.txt", 7) #7 being the line number
print line

Also, forgot this technique:

fout = open("path\\to\\test.txt", 'r')

for line in fout.readlines()[:6]: #reads up to line 7
    print line
    
fout.close()

I knew I'd finally come up with it. Here is a python solution to your problem. Unfortunately, it requires the creation of a new file ('text_out.txt') in order to work. I know it's not perfect but it's a start:

with open("text_out.txt", "w") as fout:
    with open("test.txt", "r") as fin:
        for line in fin:
            fout.write(line.replace('line 7', 'xxx'))

The next problem you face is getting the Arduino to run this code for you.

EDIT:
ok here is a solution which overwrites the test.txt file instead of making a new one. I tried this script out using a file with "lines 1-10". This probably isn't viable if the file is large:

newstuff = []
with open("path\\to\\test.txt", "r") as fout:
    for line in fout.readlines():
        newstuff.append(line.replace('line 7', 'xxx'))
        print newstuff
with open("path\\to\\test.txt", "w") as fin:
    for line in newstuff:
        fin.write(line)
fin.close()