Write into existing file with "write to text file"

Hi all,
 I have a text file that contains several lines of data (text). Now I would like to replace the first three lines with text coming from a string array.
My approach is shown in WriteToFile.vi that is attached.
When I am executing this vi (with an empty file), everything seems to be working fine in the first place.
The file will contain the following text:
oneoneone
twotwotwo
threethreethree
Now, when the third element in the array is shortened (lets say to "threethr") before execution,  the file will contain  the following text:
(the file was not emptied before execution)
oneoneone
twotwotwo
threethr
three
How can I avoid the last line being written? I have made many tests and I could not find a solution.
One more example:
Lets say we have an existing file, inside this file is:
oneoneone
twotwotwo
three
fourfourfour
Now I would like to overwrite line three with "threethreethree". Therefore I execute my vi as shown in the attachment.
What I get as a result is:
oneoneone
twotwotwo
threethreethree
ur
So, the text in line four, which should not be touched, is "ur" instead of "fourfourfour".
Any idea to solve this problem?
What I basically need is replacing a line of a text file in a conveinient way.
Thanks,
Holger
LV 8.5.1
Attachments:
WriteToFile1.jpg ‏17 KB
WriteToFile.vi ‏11 KB

The remaining fourth line is there because the third line has a <nl> at the end. You have not emptied the file so the rest of the file will be kept. This is because your line is shorter.
In the scond example the third line is longer and it will overwrite the beginning of the fourth line.
Files aren't organized in lines they are oganized in bytes. And what you write are bytes to the file even with text files.
Replacing a single line in a file is done by reading the file line by line. All unchanged lines are written to a temporary file and the line with the new text will be written instead of the original line to the temporary file. When the writting is done rename the original file, then rename the new file into the original file and then delete the renamed original file.
Waldemar
Using 7.1.1, 8.5.1, 8.6.1, 2009 on XP and RT
Don't forget to give Kudos to good answers and/or questions

Similar Messages

  • How to update an image file into existing file

    how to update an image file into existing file

    Hi,
    So, i assume you want to change one picture. On Stage, i have edgeAnimate (an image), and
    1) i am using the div tag.
    So: sym.$("edgeAnimate").css("background-image", "url(images/myImage.png)" ); will change my picture.
    Link: CSS properties.
    More CSS:
    sym.$("edgeAnimate").css( { "background-image": "url(images/myImage.png)", "background-size": "100% 100%", "background-repeat": "no-repeat", "cursor": "pointer" } );
    Using a path variable:
    var myPath = "images/myImage.png";
    sym.$("edgeAnimate").css( { "background-image": "url("+myPath+")", "background-size":"100% 100%", "background-repeat":"no-repeat", "cursor": "pointer" } );
    2) i am using the img tag.
    I can add a class using Edge Animate user interface.
    I choose one class name: "newImage".
    So:  sym.$(".newImage").css("background-image", "url(images/myImage.png)" ); will change my picture.
    Note: I assumed you don’t need to preload your picture.

  • Appending new TextLine into existing file

    I tried to add new text lines into an existing txt file. The problem is my method add new Strings on the same line (to see it you need to open the output file with notepad).
    The method invoked is:
    public static void addText( String arg0, String path ) {
              long pos;          
              try {
                   raf = new RandomAccessFile( path , "rw" );
                   pos = raf.length();
                   raf.seek( pos ); //mi sposto alla fine del file
                   raf.writeBytes( "\n" ); // new line
                   raf.writeBytes(arg0); //
                   raf.close();
              } catch (FileNotFoundException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();
         }

    To make your app system-independent use:
      String lineSeparator = System.getProperty("line.separator");as line separator
    []

  • Trouble importing objects into existing file

    I have Captivate 4 and would like to import slides/objects from file 1 to file 2.
    Everytime I do this, captivate crashes and says that it has encountered an unexpected error. It is driving me crazy,
    especially since it's not like I can copy and paste in the program. Or can I? Please help.

    Fortunately I haven't had a corrupted file or project for some time now. I put it down to never working on project files over a network and never pasting in content from other people's projects.
    But the way I used to track down corrupt elements or slides was to Save As to get a copy of my problem project and then hide or delete half the slides in the project to see if that removed the problem. If not, I try hiding or deleting the other half of the project to see if that worked.  If you find the half that has the problem, then delete half of that half and repeat the process.  Eventually, by a process of elimination, you get down to where the issue is.  Then you can go back to your main project and fix it.  Hopefully it's just a matter of recreating a slide or two.

  • Append data into the file in application server

    Hi Friends,
    I have an issue where i have a job which has three different stepst for same program. If i run the job the program will create a file in the application server and append the other two steps in the same file without overwriting the file or creating a new file.
    My problem is like its creating three different files in application server for that particular job since it has three steps . Its not appending into one particular file .
    I am using the FM 'Z_INTERFACE_FILE_WRITE' where i have used the pi_append in the exportng parameter . ITs working when i specify the file in local system. It is appending correctly when i run the report normally to apppend into local system.
    But when i schedule a job to append the file in application server its creating three different files.
    Kindly help me if anyone is aware of this issue
    Thanks in advance
    Kishore

    Hi,
    Please use open dataset to write and append files.Please check the logic of Z FM which you are using .
    To open and write into a file  use
    OPEN DATASET FNAME FOR OUTPUT.
    To append data into existing file use
    OPEN DATASET FNAME FOR APPENDING.
    To write into file:
    v_file = file path on application server
      OPEN DATASET v_file FOR output.
      IF sy-subrc NE 0.
    write:/ 'error opening file'.
      ELSE.
       TRANSFER data TO v_file.
      ENDIF.
    CLOSE DATASET v_file.
    For appending :
    OPEN DATASET v_file fOR APPENDING.(file is opened for appending data  position is set to the end of the file).
    Thanks and Regards,
    P.Bharadwaj

  • How to get all paragraphs style and their fonts of a  indesign file and write all info with para info into txt file with scripting

    how to get all how to get all paragraphs style and their fonts of a  indesign file and write all info with para info into txt file with scriptingstyle and their fonts of a  indesign file and write all info with para info into txt file with scripting

    I write the script this one works
              var par=doc.stories.everyItem().paragraphs.everyItem().getElements();
      for(var i=par.length-1;i>=0;i--)
           var font=par[i].appliedParagraphStyle.name;
            var font1=par[i].appliedFont.name;
             var size=par[i].pointSize;
            WriteToFile (par[i].contents  +   "\r" +  "Style  : " + font  + "\r" +  "FONT1  : " + font1  + "\r" +  "Size  : " + size  + "\r", reportFilePath);
                            function WriteToFile(text, reportFilePath) { 
        file = new File(reportFilePath); 
        file.encoding = "UTF-8"; 
        if (file.exists) { 
            file.open("e"); 
            file.seek(0, 2); 
        else { 
            file.open("w"); 
          file.writeln(text);  
        file.close(); 
    Thanks for all your support

  • Write to Text File.vi Output file all but first line start with tab

    The attached PNG shows the code used to build up concatenated strings into a string array for the first four lines, thence to a string Array, to Spreadsheet String.vi and, finally, the use of Write to Text File.vi
    The lower right corner shows the result loaded into a spreadsheet. Note the 3 blank entries marked by a filled red rectangle. Examination of hidden characters shows there is a tab at the beginning of lines 2, 3 and 4.
    There is no tab shown in the code. How do those tabs get there? How do I stop them?
    I have tried with the option "Convert EOL" both on and off with no difference.
    The Help states that an OS-dependent EOL character is appended to each line. I can't imagine the Windows EOL character includes a tab.
    Solved!
    Go to Solution.
    Attachments:
    Tab Mystery.PNG ‏29 KB

    wildcatherder wrote:
    I am still puzzled as to why those additional tabs were added by Array to Spreadsheet String.  I'm holding in my hand a printout of an old LabVIEW 8 program with that construction, which is known to work properly.
    Makes complete sense when you look at your code.  You build a string, including an end-of-line character, and put that string into an array.  Then, when you run it through Array to Spreadsheet String, it puts a tab after every array element, and new line at the end of each row in the array.  The first element of your array contains a new line but Array to Spreadsheet String doesn't know about it; it still inserts a tab between that array element and the next one, giving you the tabs.

  • I'm trying to share to Media Browser a 20 minute still slide show with music and text. I have tried several times to save at 1080 HD, but just before it's finished, a message box pops up saying "File already open with write permission."  What's this mean?

    I'm trying to finalize/share to Media Browser a 20 minute still slide show with music and text. I'd like to finalize it 1080 hd and have tried several times, but just before it's finished, a message box pops up saying it can't be done because "File already open with with write permission."  What does this mean?  All files are closed; this iMovie project is the only thing open.  Does it mean one of the song files from iTunes? And should I just settle for saving it as a "large" file, which is what I'm trying right now?
    Thanks,
    Jamie

    Hi
    Error -49 opWrErr  File already open with write permission
    Trash the preference files while application is NOT Running.
    from Karsten Schlüter
    Some users notice on exporting larger projects from within iMovie that this operation is aborted with an 'error -49'
    This issue occours only on MacOs machines using 10.7x
    try switching-off the Local Mobile Backup
    in Terminal copy/paste
    sudo tmutil disablelocal
    Re-launch Mac
    See also this post
    https://discussions.apple.com/thread/4434104?tstart=0
    Yours Bengt W

  • Write to text file. Append to existing file. Create file if file doesn't exist.

    Hi folks,
    up to LabVIEW 7 there was a wonderful "Write to Text File" vi which allowed the option "Append to File". Now, in LabVIEW 8, this old vi is not longer supported anymore. Instead, I am suggested to use a new "Write to Text File" vi. This vi does not offer the option "Append to File" anymore. Rather it is proposed in the online help that one should use the "Set File Position" in order to append text to the file. This much less straightforward than the old solution. Furthermore, I miss an option which would create the complete path if it doesn't exist yet.
    To summarize: Isn't there really any smart "Write to Text File" vi available which offers both the options "Append" and "Create path if file does not yet exist". Of course, I could write such a file on my own but I am sure that it is of such general interest that it already exist. In any situation, when a log file shall be written, the wanted vi would be ideal.
    Thanks a lot,
    Peter

    Ray,
    I know that the old vi is still available. See the screenshot which I attach to this message. What I am missing is an option "Create file or even complete path if file or path do not yet exist.". Is there any reason why NI doesn't provide neither this option nor a simple "Append to file" functionality in the new "Write to Text File" vi?
    Regards,
    Peter
    Attachments:
    Clipboard01.png ‏7 KB

  • How can I write new objects to the existing file with already written objec

    Hi,
    I've got a problem in my app.
    Namely, my app stores data as objects written to the files. Everything is OK, when I write some data (objects of a class defined by me) to the file (by using writeObject method from ObjectOutputStream) and then I'm reading it sequencially by the corresponding readObject method (from ObjectInputStream).
    Problems start when I add new objects to the already existing file (to the end of this file). Then, when I'm trying to read newly written data, I get an exception:
    java.io.StreamCorruptedException
    at java.io.ObjectInputStream.readObject0(Unknown Source)
    at java.io.ObjectInputStream.readObject(Unknown Source)
    Is there any method to avoid corrupting the stream? Maybe it is a silly problem, but I really can't cope with it! How can I write new objects to the existing file with already written objects?
    If anyone of you know something about this issue, please help!
    Jai

    Here is a piece of sample codes. You can save the bytes read from the object by invoking save(byte[] b), and load the last inserted object by invoking load.
    * Created on 2004-12-23
    package com.cpic.msgbus.monitor.util.cachequeue;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    * @author elgs This is a very high performance implemention of Cache.
    public class StackCache implements Cache
        protected long             seed    = 0;
        protected RandomAccessFile raf;
        protected int              count;
        protected String           cacheDeviceName;
        protected Adapter          adapter;
        protected long             pointer = 0;
        protected File             f;
        public StackCache(String name) throws IOException
            cacheDeviceName = name;
            f = new File(Const.cacheHome + name);
            raf = new RandomAccessFile(f, "rw");
            if (raf.length() == 0)
                raf.writeLong(0L);
         * Whne the cache file is getting large in size and may there be fragments,
         * we should do a shrink.
        public synchronized void shrink() throws IOException
            int BUF = 8192;
            long pointer = getPointer();
            long size = pointer + 4;
            File temp = new File(Const.cacheHome + getCacheDeviceName() + ".shrink");
            FileInputStream in = new FileInputStream(f);
            FileOutputStream out = new FileOutputStream(temp);
            byte[] buf = new byte[BUF];
            long runs = size / BUF;
            int mode = (int) size % BUF;
            for (long l = 0; l < runs; ++l)
                in.read(buf);
                out.write(buf);
            in.read(buf, 0, mode);
            out.write(buf, 0, mode);
            out.flush();
            out.close();
            in.close();
            raf.close();
            f.delete();
            temp.renameTo(f);
            raf = new RandomAccessFile(f, "rw");
        private synchronized long getPointer() throws IOException
            long l = raf.getFilePointer();
            raf.seek(0);
            long pointer = raf.readLong();
            raf.seek(l);
            return pointer < 8 ? 4 : pointer;
         * (non-Javadoc)
         * @see com.cpic.msgbus.monitor.util.cachequeue.Cache#load()
        public synchronized byte[] load() throws IOException
            pointer = getPointer();
            if (pointer < 8)
                return null;
            raf.seek(pointer);
            int length = raf.readInt();
            pointer = pointer - length - 4;
            raf.seek(0);
            raf.writeLong(pointer);
            byte[] b = new byte[length];
            raf.seek(pointer + 4);
            raf.read(b);
            --count;
            return b;
         * (non-Javadoc)
         * @see com.cpic.msgbus.monitor.util.cachequeue.Cache#save(byte[])
        public synchronized void save(byte[] b) throws IOException
            pointer = getPointer();
            int length = b.length;
            pointer += 4;
            raf.seek(pointer);
            raf.write(b);
            raf.writeInt(length);
            pointer = raf.getFilePointer() - 4;
            raf.seek(0);
            raf.writeLong(pointer);
            ++count;
         * (non-Javadoc)
         * @see com.cpic.msgbus.monitor.util.cachequeue.Cache#getCachedObjectsCount()
        public synchronized int getCachedObjectsCount()
            return count;
         * (non-Javadoc)
         * @see com.cpic.msgbus.monitor.util.cachequeue.Cache#getCacheDeviceName()
        public String getCacheDeviceName()
            return cacheDeviceName;
    }

  • Write to text file returns no error even if the underlying file is deleted

    Hi,
    I'm using a CompactRIO and writing to a text file underneath the C drive.
    I'm running into an unexpected situation when I am trying to error check my file handling.  I assumed that if the underlying file being written to that was created by open/create/replace vi and written to with the "Write to Text File" vi, would return an error if I delete the file from underneath it in the file system., yet there is no reported error and the function carrys on seemingly successfully writing to a file that has been deleted.  
    Anyone know why this happens and how to potentiallly remedy?

    Ouch, this obviously isn't ideal but is probably down to the filesystem on the CompactRIO.
    I would consider putting in a check - doing something like getting the file position from the file might return an error if the file no longer exists.
    Certified LabVIEW Architect, Certified TestStand Developer
    NI Days (and A&DF): 2010, 2011, 2013, 2014
    NI Week: 2012, 2014
    Knowledgeable in all things Giant Tetris and WebSockets

  • Write to text file; not overwriting old, but moving to next entry and writing

    I am interested in writing a series of filenames, to a text file, so I can keep track of sample ID and experiment #'s. I would like each new filename to be writtten following the previous filename, rather than always overwriting. I've done a brief check of some of the properties, and couldn't find anything. Any ideas? thanks

    Hey csmrunman,
     Just to clarify, are you looking to append text to an existing file without over-writing existing text, or are you looking to create a series of text files with unique names?  If you want to append text to an existing file, then Andrey's solution above should be what you need.  If you want to programmatically determine a unique name for the text files, then you can use a similar means to deterine a unique name (Andrey used the iteration terminal above so that each iteration of the while loop produces a unique text to be inserted into the text file).  You mentioned the use of sample ID and experiment number, which you could also use as a file name if you wish to, and even have the user of the VI enter the information that makes up the filename through front panel controls.  The string functions (in the Functions Palette under Programming » String) will be of great use here.  Of course, if you are just looking for an “out-of-the-box” solution, there is always the Write to Measurement File Express VI (Programming » File I/O), but this is best suited for situations where you have channels of data that you would like to store, so this may not fit depending on the data you wish to store.  If it does fit, however, there are settings that you can configure for saving to a series of files:
    Message Edited by Chris_G. on 09-28-2009 11:50 AM
    Chris_G
    Sr Test Engineer
    Medtronic, Inc.

  • How to write data into a file

    Hi
    I want to write data from a string into a file. I am created a directory and a .doc file . But when i write this data from a string into .doc file , its give an error : File not found exception
    But, when i check in my directory, a file is created with blank.
    My code is:
    import java.io.*;
    import java.util.*;
    import java.lang.*;
    class createFile {
         public static void main(String[] args) {
    try {
         String mss = "This is for dedo";
         FileInputStream fis;
         FileOutputStream fos;
    File file = new File("C:\\JD\\m4.rtf");
    // Create file if it does not exist
    boolean success = file.createNewFile();
         success = true;
    if (success) {
                   System.out.println("suc");     
                   fis = new FileInputStream(mss);
                   System.out.println(fis);
              fos = new FileOutputStream(file);
              int c;
                   while ((c = fis.read()) != -1) {
         fos.write(c);
                   System.out.println("mss");
              fis.close();
              fos.close();
         System.out.println("created");
    // File did not exist and was created
    } else {
    // File already exists
    } catch (IOException e) {
         System.out.println(e);
    regards
    madhu

    InputStream inputStream = new ByteArrayInputStream(mss.getBytes());Use this to push into the file>
    Ummm.... no. InputStreams are for reading, not for writing.
    Anyway, OP, you're making a mistake. You're trying to open a stream to a file called "This is for dedo". Use FileOutputStream(File file) constructor or FileOutputStream(String pathToFile). You can then wrap that stream with a PrintWriter or whatever you need.

  • Write to text file (including spaces/next line) using oracle??

    How to write to text file using oracle? And how do I handle spaces/next line? (i was trying to use spaces(ch(32)), however it is just converted into squares in the text file.) thanks!

    989873 wrote:
    How about tabs?It does not matter what character it is. UTL_FILE deals correctly with any text file. Tabb is CHR(9):
    SQL> declare
      2       v_file utl_file.file_type;
      3       v_total_rec number := 0;
      4       v_total_sal number := 0;
      5  begin
      6      v_file := UTL_FILE.FOPEN('TEMP','TEST.TXT','w');
      7      for v_rec in (select * from emp) loop
      8        v_total_rec := v_total_rec + 1;
      9        v_total_sal := v_total_sal + v_rec.sal;
    10        UTL_FILE.PUT_LINE(
    11                          v_file,
    12                          lpad(v_rec.deptno,2) || chr(9) || rpad(v_rec.ename,14) || chr(9) || to_char(v_rec.sal,'99999D99')
    13                         );
    14      end loop;
    15      UTL_FILE.PUT_LINE(v_file,'Total Salary:' || chr(9) || v_total_sal);
    16      UTL_FILE.PUT_LINE(v_file,'Total Records:' || chr(9) || v_total_rec);
    17      UTL_FILE.FCLOSE(v_file);
    18  end;
    19  /
    PL/SQL procedure successfully completed.
    SQL> declare
      2       v_file utl_file.file_type;
      3       v_line varchar2(100);
      4  begin
      5      v_file := UTL_FILE.FOPEN('TEMP','TEST.TXT','r');
      6      loop
      7        UTL_FILE.GET_LINE(v_file,v_line);
      8        DBMS_OUTPUT.PUT_LINE(v_line);
      9      end loop;
    10    exception
    11      when no_data_found
    12        then
    13          UTL_FILE.FCLOSE(v_file);
    14  end;
    15  /
    20      SMITH              800.00
    30      ALLEN             1600.00
    30      WARD              1250.00
    20      JONES             2975.00
    30      MARTIN            1250.00
    30      BLAKE             2850.00
    10      CLARK             2450.00
    20      SCOTT             3000.00
    10      KING              5000.00
    30      TURNER            1500.00
    20      ADAMS             1100.00
    30      JAMES              950.00
    20      FORD              3000.00
    10      MILLER            1300.00
    Total Salary:   29025
    Total Records:  14
    PL/SQL procedure successfully completed.
    SQL>SY.

  • Write to text file while scrolling table issue

    Hi all,
    I have a LabVIEW application that logs data using 'write to text file' every second. This is a bckground task in a sub-VI. On the main screen I have several tables that have scrollbars. Every time the file is written the scrolling of a table is effectivley canceled. It is then necessary to click on the scrollbar again to re-start scrolling the table. I guess this is an issue with the OS but not sure yet. I have not tested other operating systems yet. I thought I would try the forum first. Has anyone else experienced this issue? Any ideas on how to fix this?
    I have tried using list boxes instead of tables but the same issue exists.
    I'm using windows 7 and LabVIEW 2011.
    Thank you.
    Certified LabVIEW Architect

    Hi Steve, thanks for offering to help. Right now I'm on a machine with LabVIEW 2010 and XP and the issue does not exist. But I have created a little test VI that should demonstrate the issue once running on LabVIEW 2011 SP1 and Windows 7. I can't confirm this VI will demonstrate the issue until later today when I can test it on the problem system myself. Feel free to give it a go and let us know what you find, or wait until I confirm the attached VI will demonsrate the issue (10 to 12 hrs time).
    Thank again.
    Certified LabVIEW Architect
    Attachments:
    Table scroll test_1.vi ‏13 KB

Maybe you are looking for