Write at the beginn of a File (.py)



  • Hey,

    i want to write into a File (Python-File).
    Now i have a Problem:
    When i write somethin into the File it append at the end !
    Follow the Code:

    
        QFile file("C:/Users/Test/Desktop/Projekt/write.py");
        if(file.open(QIODevice::ReadWrite | QIODevice::Append | QIODevice::Text))
        {
            QTextStream stream(&file);
            stream << "test = 'TestFile.csv' ";
        }
    

    i want to write at the top of the File (first or secound line)

    Someone have a Idea why the code writed at the end of the File?


  • Lifetime Qt Champion

    Hi
    Yes, you ask it to with QIODevice::Append
    if(file.open(QIODevice::ReadWrite | QIODevice::Append | QIODevice::Text))
    try with
    QIODevice::Truncate
    instead

    This assumes you mean, you just want to overwrite the file.

    If you actually want to insert text line in the top of a file
    then see next post :)


  • Qt Champions 2018

    QFile file("C:/Users/Test/Desktop/Projekt/write.py");
    if(file.open(QIODevice::ReadOnly | QIODevice::Text)) {
      QString oldFile;
      QTextStream rstream(&file);
      oldFile = rstream.readAll() ;
      file.close();
      if(file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream wstream(&file);
        wstream << "test = 'TestFile.csv' " << oldFile;
      }
    }
    


  • @NotYourFan
    If your intention is to insert some new lines at the start of an existing file while retaining all its subsequent content, you must do it @VRonin's way, i.e. you cannot truly "insert" and move subsequent things downward, you must implement either by reading in the whole existing file and only then starting to rewrite to the file ( @VRonin's code, but don't use that if your file is "large" :) ), or by writing to a separate new file, inserting and then copying from the old file as required.



  • This post is deleted!


  • Oh now i have another problem ...

    at the first four lines are my imports for the script:

    import csv
    import re
    import json
    import math

    i want that to write now "test = 'TestFile.csv'"
    at the fifth line, to looks like this:

    import csv
    import re
    import json
    import math
    
    test = 'TestFile.csv'
    

  • Qt Champions 2018

    @NotYourFan Then open the file in Append mode and append empty line and the other one...



  • With the Append mode i write my stream at the bottem ... thats the Problem.



  • @NotYourFan
    @jsulm is getting confused with the example you have given. He is assuming the line you want to add is right at the end, but you mean somewhere in the middle, there is still more stuff after it in the file. Just ignore any mentions of "append".

    Look, as I have said, you're probably best here just reading line-by-line from the old file, inserting whatever you want as you go writing it out to a new file. Then delete original and rename new to old at the end. This is always a good idea, as you don't overwrite your existing file with partial stuff if for whatever reason you have an error in your code or something. This is a common way to alter existing files. Just do it this way....

    A completely separate question is why you want to rewrite an existing Python code file anyway? You may have your reasons. But if we took just your example of "injecting" that line into the source, are you sure it could not be achieved better by passing TestFile.csv on the command line at run time as an argument to your Python executable??


  • Moderators

    @NotYourFan

    QFile file("C:/Users/Test/Desktop/Projekt/write.py");
    if(file.open(QIODevice::ReadOnly | QIODevice::Text)) {
      QTextStream rstream(&file);
      QVector<QString> v;
       while(! rstream.atEnd())
            v.append(rstream.readLine());
      file.close();
      if(file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QTextStream wstream(&file);
    
        for(int i(0); i < v.size(); i++){
             if( i == 5)
                 wstream <<  "test = 'TestFile.csv' " 
            wstream << v.at(i);
    
        }
        file.close();
      }
    }
    

    edit: fixed some typos, auto correct can be a pain, sometimes.



  • @J.Hilk
    I don't wish to start an argument or sound rude, but why encourage to read the whole file into memory when it's just as simple to do it line by line (at least in OP's case) as you go? Plus read-from-old-write-to-new doesn't suffer from blatting the original when the programmer makes a coding error! :) Anyway it's preference for the OP.


  • Moderators

    @JonB Simple,
    I took the liberty to copy and past @VRonin example from before and edit it ;-)



  • @J.Hilk
    Lol! :) OK, I commented on that earlier, far be it for us to disagree with the venerable @VRonin :) Anyway, the OP can do it either way as he sees fit.



  • @J-Hilk

    Wehen i run your code, my .py scriptcode changed complete to only ONE Row.


  • Moderators

    @NotYourFan
    the example is not checked, I don't have a +py file for that.

    Obviously you need to add a new line character at the end of each line.

    if( i == 5)
                 wstream <<  "test = 'TestFile.csv' "  << "\n";
            wstream << v.at(i) << "\n";;
    


  • This post is deleted!


  • @J-Hilk
    now it works the problem is when i changed the wstram it doesent override.

    i get " test = 'Hallo221.csv' test = 'Hallo1.csv' ...."

    how i can override?

    thx



  • @NotYourFan
    What does "override" mean? Do you mean "overwrite" what is already in wstream? Do you mean wstream.seek(0)?



  • yeah sry,

    i mean "overwrite".

    i always get " test = 'Hallo221.csv' test = 'Hallo1.csv' test = 'Hallo12321.csv' .....

    but i want to get only "test = 'Hallo12321.csv' so i want to "overwrite" the line 5 and not add a new string



  • @NotYourFan
    So did you try my wstream.seek(0)? after the first write and before the second?
    Or, depending on just what you intend by "overwrite", you may need to wstream.resize(0).
    Try with both "first-string-is-long", "second-is-short" and then with "first-is-short", "second-string-is-long" to see the difference between seek(0) vs resize(0).


  • Moderators

    @NotYourFan

    You're doing fishy stuff, that may break at any point. 
    You should rethink what you're actually trying to do.

    for(int i(0); i < v.size(); i++){
             if( i == 5) {
                 wstream <<  "test = 'TestFile.csv' "   << "\n";
                if(v.at(i).contains("test = '"))
                    continue;
             }        
             wstream << v.at(i)  << "\n";
        }
    


  • @J.Hilk
    PERFEKT !!!!!
    THANK YOU SO MUTCH


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.