Jump to content

Delete a line from a txt file?


Naufuge
 Share

Recommended Posts

i can help u, but i need u to be more specific.....after u delete that line, will the whole txt file be empty?? do u only want to delete the first line?? etc...i need to know a lil more so i can give u the right functions to use

GodandRock leaves his mark. ^*+-._.-+*^(|{[\:=^*+-._ GAR _.-+*^=:/]}*^|)^*+-._.-+*^

[font="Fixedsys"][size="3"][u][font="Franklin Gothic Medium"] [/font][/u][/size][/font]

Link to comment
Share on other sites

I need to be able to select a file from a list view in my gui, which i have so it registers a var equal to which line in the list view is selected, then if you press the delete button from the menu in the gui, i need it to only delete that line of the txt file.

Link to comment
Share on other sites

im sorry but im not getting u, do u want to delete a file or just a line?? and also im not familiar with treeviewlist...and i think that functions only selects files, and not the content the files have...

GodandRock leaves his mark. ^*+-._.-+*^(|{[\:=^*+-._ GAR _.-+*^=:/]}*^|)^*+-._.-+*^

[font="Fixedsys"][size="3"][u][font="Franklin Gothic Medium"] [/font][/u][/size][/font]

Link to comment
Share on other sites

ok... I made a Gui, that has a listview. When i click on a line in the list and click "File>Delete", i need it to read what is selected (that part is done) then read a txt file, and delete only the line that is equal to the line selected.

The txt file contains many lines like:

GUICtrlCreateListViewItem("BLAH|BLAH|BLAH") So it shows up in the GUI's ListView

For example:

filedelete0un.th.png

(You may have to save pic and zoom in, i had to resize it.)

Ok i think its too blury, it shows the gui, with a line selected, and the drop down menu with the Delete item selected.

I need to delete the selected line, so that when the gui is updated or reloaded that line is no longer in the GUI's ListView.

Does that explain it??

Edited by Naufuge
Link to comment
Share on other sites

lol?

as i understood he wants to delete a LINE from a textfile, and no control...

i can't find a function in the helpfile to delete a line from a textfile, but you could try to delete the textfile and write everything instead of the line again...

you could make a temporary copy of the file, too and could read all lines instead of the line you don't wanted to have with a loop and the FileReadLine ( filehandle or "filename" [, line] ) function...

Link to comment
Share on other sites

maybe u can do sumtin like the "filereadline" function....then assign it a variable like $1...then do

If $1 = "blablabla"
Then
;do stuff here

and also, im SURE theres an answer for this out there, just search for it, i think this kind of thing has been answered

GodandRock leaves his mark. ^*+-._.-+*^(|{[\:=^*+-._ GAR _.-+*^=:/]}*^|)^*+-._.-+*^

[font="Fixedsys"][size="3"][u][font="Franklin Gothic Medium"] [/font][/u][/size][/font]

Link to comment
Share on other sites

lol?

as i understood he wants to delete a LINE from a textfile, and no control...

i can't find a function in the helpfile to delete a line from a textfile, but you could try to delete the textfile and write everything instead of the line again...

you could make a temporary copy of the file, too and could read all lines instead of the line you don't wanted to have with a loop and the FileReadLine ( filehandle or "filename" [, line] ) function...

ok, i was trying to find a way that would work faster than rewriting all the lines except one, but i guess ill give it a go ahead.

BTW does anyone know when the next release of autoit v3 will be, not a Beta release?

Link to comment
Share on other sites

hm, the next release will come soon... the beta is always at v. 3.1.1.93... but if you don't do so you should dl the beta-versions too... theyre very stable and have new features...

humm, it works very fast if you do it with a loop... fe:

FileCopy("Bla.txt", "Bla_Copy.txt")
FileDelete("Bla.txt")
For $i = 1 to 10 Step 1
   $Text = FileReadLine("Bla_Copy.txt", $i)
   FileWriteLine("Bla.txt", $Text)
Next
For $i = 12 to 100 Step 1
   $Text = FileReadLine("Bla_Copy.txt", $i)
   FileWriteLine("Bla.txt", $Text)
Next
FileDelete("Bla_Copy.txt")

Argh, sry for my slow answer, but thats all you need... With this Code the program copies all lines from 1 to 100 except 11 to the new file...

Edited by Lord_Doominik
Link to comment
Share on other sites

Thank you for your help, i modded your coding alittle to fit my needs but all in all yours worked. heres what i used

Func File_Delete()
    $Selected_Setting = GuiCtrlRead($Setting_List)
    $Selected_Setting = $Selected_Setting - 30
    MsgBox(48,"Title",$Selected_Setting)
        If $Selected_Setting = -30 Then
            MsgBox(48,"Gui Error - Delete","No Setting Selected, please Select a Setting then try again.")
        Else
            $Read_Line = 1
            Do
                If $Read_Line = $Selected_Setting Then
                Else
                    $Stored_Line = FileReadLine(@ScriptDir & "\Configuration Files\Settings.dbl",$Read_Line)
                    FileWriteLine(@ScriptDir & "\Configuration Files\Temp_Settings.dbl",$Stored_Line)
                EndIf
                $Read_Line = $Read_Line + 1
            Until $Stored_Line = ""
            FileDelete(@ScriptDir & "\Configuration Files\Settings.dbl")
            FileCopy(@ScriptDir & "\Configuration Files\Temp_Settings.dbl",@ScriptDir & "\Configuration Files\Settings.dbl")
            FileDelete(@ScriptDir & "\Configuration Files\Temp_Settings.dbl")
            FileWrite(@ScriptDir & "\Configuration Files\Temp_Settings.dbl","")
        EndIf
    Update_SettingList()
EndFunc

and it seems to work fine. (Except that G^Y Updat_SettingList() lol, i still cant figure out how to update the Gui without having to reload everything.) oh well, i should probably get to bed, its 10:34 Here.

Thank you again for your help

ps. Thats fine having a slow reply, im just glad you could help

Link to comment
Share on other sites

hm, np for help!

that's a way too, but with your script it only copies all lines until it reachs the empty one... the lines after the emtpy line aren't copied to the file... but it's a way, too and it's good, too... if you take a do-until or a for-next loop is a point of the programming style, but i rather take for-next loops.

i don't understand why you first delete your temp copy and than write an empty line to it... but all in all it's a good script.

in germany it was about 4-5 am ^^...

hm, why do you want to refresh the gui?

i think it's funny, much of your problems i had too, earlier...

there are some ways, but again no simple function or something to refresh a gui. you could solve it, with simple writing the part, where the gui is created into a function, and delete the gui, when you want to refresh... then you can call the function and everything will "refresh"... but it looks not very good and if you could say some more information why you want to refresh it i can help you finding a better way. if you f.e. only want to refresh the gui, because you want to refresh your listview and not the buttons ect. then there are some better ways...

Edited by Lord_Doominik
Link to comment
Share on other sites

Hi,

You will find SlimShady has a "replaceLine" (so replace with empty ? Delete?...) func in his Misc UDF; also copied to my "DOScoms.au3" (link from signature)

_ReplaceLineDOS($File, $lineNum, $NewLine)

_ReplaceLineNODOS($File, $lineNum, $NewLine)

You may see that i have a plan to do the Word-object (with beta) based on "_ReplaceLineNODOS($File, $lineNum, $NewLine)" in that UDF too; I haven't got there yet.

Anybody keen?

Best Randall

; to be fixed (from Word macro)

;Sub ReplaceLine()

;Dim o_Line As Paragraph

;ReplaceString = "========================================="

;FindString = "Auth"

;For Each oPrg In Activedocument.Paragraphs

; If InStr(o_Line.Range.Text, FindString) Then

; o_Line.Range.InsertAfter Text:=ReplaceString

; o_Line.Range.Delete

; End If

;Next

;End Sub

Link to comment
Share on other sites

I need to refresh the gui so that when you delete a line from the list you dont have to reload the program to view the changes, i cant put it into a function because it "#includes" a file and you cant include the same file twice, so... I dont know.

Thanks again

Ps. I deleted the temp_setting file and re wrote it with "" because when my program saves, it saves to a temp txt file, then after you click File>Save it writes them to the actual file, then emptys the temp file. (for orginazation, that way if you want to delete everything youve done, while you were just running it you can just close, instead of having to click on File>Delete for all the Items you dont want.

Link to comment
Share on other sites

I need to refresh the gui so that when you delete a line from the list you dont have to reload the program to view the changes, i cant put it into a function because it "#includes" a file and you cant include the same file twice, so... I dont know.

Reread the Help file on #includes and UDFs

At the top of your script... add

#include <File.au3>

#include <Array.au3>

if they are not already there. Even if you had them listed 4 times, each would only load once.

Below is a UDF to create/update a ListView.

Func _BuildListView()
    $listview = GUICtrlCreateListView("Name|Activity|Trial|Time|Date", 8, 75, 250, 270, BitOR($GUI_SS_DEFAULT_LISTVIEW, $LVS_SORTASCENDING, $LVS_NOSORTHEADER, $WS_HSCROLL), $LVS_EX_GRIDLINES)
    $sListData = ""
    $sListName = ""
    $sListName = $sCurrName
    $aVar1 = IniReadSectionNames($sDataPath & $sListName & ".ini")
    For $i1 = 1 To $aVar1[0]
        If $aVar1[$i1] <> "Name" And $aVar1[$i1] <> "Style_Location" And $aVar1[$i1] <> "DefaultActivity" And $aVar1[0] > 3 Then
            $sActivity = $aVar1[$i1] & "|"
            $aVar2 = IniReadSection($sDataPath & $sListName & ".ini", $aVar1[$i1])
            If @error Then
                MsgBox(4096, "Error 1417", "Error occured, unable to read the section (The INI file may not exist or the section may not exist) or if the section was empty, or no standard format data could be found.")
            Else
                If $aVar2[0][0] > 1 Then
                    For $i2 = 1 To $aVar2[0][0]
                        If StringLeft($aVar2[$i2][0], 7) <> "Trial00" Then
                            If StringInStr($aVar2[$i2][1], "/") Then
                                $sListData = $sListName & "|" & $sActivity & StringRight($aVar2[$i2][0], 2) & "|" & StringLeft($aVar2[$i2][1], 6) & "|" & StringRight($aVar2[$i2][1], 10)
                            Else
                                $sListData = $sListName & "|" & $sActivity & StringRight($aVar2[$i2][0], 2) & "|" & StringLeft($aVar2[$i2][1], 6) & "|No date"
                            EndIf
                            GUICtrlCreateListViewItem($sListData, $listview)
                            $sListData = ""
                        EndIf
                    Next
                EndIf
            EndIf
        ElseIf $aVar1[0] = 3 Then
            GUICtrlCreateListViewItem(" | | | | ", $listview)
        EndIf
    Next
EndFunc;==>_BuildListView

It does it from an array, in this case the array is created in the function, but the array could have been created elsewhere in my script. I created the array and converted it to GUI Data format here because the file is short and I had changed it elsewhere in the script. In your case you could load the file directly into an array and process it for a ListView before writing the GUI or at any later time when you have made a change in the data.

I used

If StringLeft($aVar2[$i2][0], 7) <> "Trial00" Then
    If StringInStr($aVar2[$i2][1], "/") Then
        $sListData = $sListName & "|" & $sActivity & StringRight($aVar2[$i2][0], 2) & "|" & StringLeft($aVar2[$i2][1], 6) & "|" & StringRight($aVar2[$i2][1], 10)
    Else
        $sListData = $sListName & "|" & $sActivity & StringRight($aVar2[$i2][0], 2) & "|" & StringLeft($aVar2[$i2][1], 6) & "|No date"
    EndIf
    GUICtrlCreateListViewItem($sListData, $listview)
    $sListData = ""
EndIf

to convert the array to GUI Data format. That was before I learned about the StringReplace() function or maybe it was because the data was in a two demensional array. Anyway, assuming that each line in your file is a record and that you are displaying all of it in the listview, you could load the file into an array.

Dim $asYourFileContent
If Not _FileReadToArray("yourfilename.ext",$asYourFileContent) Then
   MsgBox(4096,"Error", " Error reading yourfilename.ext to Array    error:" & @error)
   Exit
EndIf

You'll want to sort the array into the same order as the ListView, that way when you determine the index of the record in the listview, it will be the same index of the coresponding record in the array to delete a record from the array.

Use

_ArraySort($asYourFileContent, 1, 1);The first 1 specifies Descending

or

_ArraySort($asYourFileContent, 0, 1);The 0 specifies Ascending, the 1 excludes the first array element.
                                        ;Note: the first element contains the number of records in the array

If the fields of your records are not separated by '|' a verticle line often called a "pipe', you will need to convert the separators into pipes. To do that there are at least two strategies, I'm going to show you one that assumes you don't always know exactly how many lines or fields are in the file (it'll work even if you do know).

I'm also going to assume that you are using TABs to separate the fields, if you use something else just replace the @TABs with whatever you do use in the code below.

For $x = 1 to $asYourFileContent[0]
    While StringInStr($asYourFileContent[$x], @TAB) > 0
        $asYourFileContent[$x] = StringReplace($asYourFileContent[$x], @TAB, "|")
    WEnd
    $sListData = $asYourFileContent[$x]
    GUICtrlCreateListViewItem($sListData, $listview)
Next

Now about deleting a record

$iElement = The index of the ListView record to be deleted.

_ArrayDelete ( $asYourFileContent, $iElement )

First after deleting the array record you'll want to refreshe the ListView and write the array to the file so the array and the file will be in agreement.

Refreshing the List View

For $x = 1 to $asYourFileContent[0]
    $sListData = $asYourFileContent[$x]
    GUICtrlCreateListViewItem($sListData, $listview)
Next

Before rewiting the file, you may want to reconvert the field separators in the array records. Just reverse the conversion above.

Then use

_FileWriteFromArray("yourfilename.ext", $asYourFileContent )

to write the changed data to the file

This, and reviewing the Help file for each function and UDF that I have used should be enough for you to put it together. Try it several times and if you just can't get it say how and where it fails and list the pertinent portions of your script and I'll point out the problems and how to fix them. The more you try, the more you'll understand. I'm confident of the concepts I've used, but I'm always subject to typos, so review the function and UDF syntax carefully. The methods shown here are much more efficient/quicker than a line-by-line read or a line-by-line write.

Gene

Edited by Gene

[font="Verdana"]Thanks for the response.Gene[/font]Yes, I know the punctuation is not right...

Link to comment
Share on other sites

Hi @Gene!

Such a great and detailed reply!

I wonder if you would like to help me add "deleting lines and columns" to the "ArrayView" in my array2D UDF (from signature)?... I just haven't got there;

It needs re-writing as it is all a hack; though I think the concept is good for making it an easy-to use function that we don't all have to keep re-writing?

Interested in your thoughts,

Randall

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...