Jump to content

Read all text files in a directory to various arrays


Recommended Posts

#include <file.au3>
#include <array.au3>
$filelist = _FileListToArray(@scriptdir&"\SAP\data\","*.txt")
If @Error=1 Then
    MsgBox (0,"","No Files\Folders Found.")
    Exit
EndIf
$x=1
while $x <= $filelist[0]
    $filelist[$x] = StringTrimRight($filelist[$x],4)
    _FileReadToArray(@ScriptDir&"\SAP\data\"&$filelist[$x], eval($filelist[$x]));----------ERROR: _FileReadToArray() called with Const or expression on ByRef-param(s).
    $x = $x + 1
WEnd

in side the folders SAP\Data\ I have about 40 text files containing information that get read to arrays of the same name as the text files. For example one text file is named wsnlist.txt and the array it gets read to is $wsnlist. Right now I'm doing this manually but it looks messy and I wanted to shorten the number of lines used.

Any Suggestions?

What are we going to do tonight Brain?Same thing we do every night Pinky try to automate the world.

Link to comment
Share on other sites

You need to supply _FileReadToArray with another array variable as a parameter (to store the contents of the file being read).

From help: _FileReadToArray($sFilePath, ByRef $aArray)

Also,

'If @Error=1 Then' is better checked as 'If @error Then'

And,

$x=1

while $x <= $filelist[0]

...

$x = $x + 1

WEnd

Is better written as

For $x=1 to $filelist[0]
...
Next
Edited by DaRam
Link to comment
Share on other sites

  • Moderators

Negative1,

I do not believe that AutoIt will allow you to do what you want. After my abortive attempts to do it, I went for a good trawl through the forums and found this snippet from PSaltyDS:

"I think what he wants to do would be equivalent to:

$sVar = "ABC"
Assign ($sVar & [3], '["Zero", "One", "Two"]')

And have that give the same result as:

Dim $ABC[3] = ["Zero", "One", "Two"]

But the syntax is invalid for AutoIt, and I don't know a way to declare an array with the contents of a string variable for the name."

That looks very much like what I believe you are trying to do - and if PSaltyDS says it cannot be done, I am inclined to believe him. :-(

However, is it so important that the arrays have the same names as the files? You could save the various arrays as elements within a larger array and put the file name as an element of the array. Here is a rough script which shows what I mean (you will have to adjust the paths of course):

#include <file.au3>
#include <array.au3>

$filelist = _FileListToArray(@scriptdir, "*.au3")
If @Error=1 Then
    MsgBox (0, "", "No Files\Folders Found.")
    Exit
EndIf

Global $file_arrays[$filelist[0] + 1]

For $i = 1 To $filelist[0]
    $array_name = StringTrimRight($filelist[$i], 4)
    _FileReadToArray(@ScriptDir & "\" & $filelist[$i], $file_arrays[$i])
    _ArrayInsert($file_arrays[$i], 0, $array_name)
    _ArrayDisplay($file_arrays[$i])
Next

This way you can identify the array by the name stored within it - would that be good enough?

Sorry I cannot be of any more help.

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Turn off compile warnings and this works...

#Region;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Run_AU3Check=n
#EndRegion;**** Directives created by AutoIt3Wrapper_GUI ****

Dim $ABC[3] = ["Zero", "One", "Two"]
$sVar = "XYZ"
Execute(Assign($sVar, $ABC))
_ArrayDisplay($XYZ)

;------------------------------------------------------------
#include <file.au3>
#include <array.au3>
Dim $array
$filelist = _FileListToArray(@scriptdir,"*.txt")
If @Error Then
    MsgBox (0,"","No Files\Folders Found.")
    Exit
EndIf
For $x = 1 to $filelist[0]
    $tmp = StringTrimRight($filelist[$x],4)
    _FileReadToArray(@ScriptDir&"\"&$filelist[$x], $array)
    $array[0] = $tmp & "," & $array[0]; insert name into 0 element
    Execute(Assign($tmp, $array))
Next
_ArrayDisplay($med); stick in the name of a file in $FileList and you'll see the array has been created

But I don't think I'd want to go this route, I'd probably just maintain $FileList as an index to match up with the $FileArrays arrays that Melba23 demonstrated building below.

Link to comment
Share on other sites

  • 1 year later...

Hi, I'm trying to read $file_arrays into a new array, so that the new array

should hold the whole file in a single element. It's ok when I read it into

a single variable, like this one:

$result = _ArrayToString($file_arrays[1], Stringformat("\r\n"), 1)

Shortly I could not design $result[$i] such that $result[2] should hold the whole

file. Certainly a new for next loop is needed.

Any help is appreciated.

Thanks

Note: the last array display command in the code below is omitted, showing that sonuc array is not created.

#include <file.au3>
#include <array.au3>
#include <GUIConstants.au3>

$FileList=_FileListToArray("C:\Deneme\","*.txt")
If @Error=1 Then
    MsgBox (0, "", "No Files\Folders Found.")
    Exit
EndIf

Global $file_arrays[$filelist[0] + 1]


For $i = 1 To $filelist[0]
    $array_name = StringTrimRight($filelist[$i], 4)
    _FileReadToArray("C:\Deneme\" & "\" & $filelist[$i], $file_arrays[$i])
    _ArrayInsert($file_arrays[$i], 0, $array_name)
    _ArrayDisplay($file_arrays[$i])

Next

dim $sonuc[4]

for $i = 1 to ubound($filelist[0])
$sonuc[$i] = _ArrayToString($file_arrays[$i], Stringformat("\r\n"), 1)
next

If IsArray($sonuc) then
_ArrayDisplay($sonuc[$i])
endif
Edited by msalperen
Link to comment
Share on other sites

  • Moderators

msalperen,

It is much easier to read the file content directly rather than recreate it from the array: :)

#include <File.au3>
#include <Array.au3>

$aFileList = _FileListToArray(@Scriptdir, "*.au3")
If @error=1 Then
    MsgBox (0, "", "No Files\Folders Found.")
    Exit
EndIf

Global $aFileStrings[$aFileList[0] + 1][2] = [[$aFileList[0]]]

For $i = 1 To $aFileList[0]
    ; Add file name to [n][0] element
    $aFileStrings[$i][0] = $aFileList[$i]
    ; Read file content
    $sFile = FileRead(@ScriptDir & "\" & $aFileList[$i])
    ; Add file content to [n][1] element
    $aFileStrings[$i][1] = $sFile
Next

_ArrayDisplay($aFileStrings)

If I have misunderstood what you wanted to do, please explain it again! ;)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Melba23,

Thank you very much. This is exactly what I want. I should admit that this is the best programming forum I have ever seen. Thanks again.

Edit

Could this solution be generalized as "FolderReadToArray" function or would it be over-simplification?

Edited by msalperen
Link to comment
Share on other sites

  • Moderators

msalperen,

Could this solution be generalized as "FolderReadToArray" function

I would say there is no chance of getting such a function into the main release as I can see very little general use for it. But there is nothing to stop you turning it into a function within a personal #include file. ;)

AutoIt looks for #include files in 3 places:

- 1. C:\Program Files\AutoIt3\Include (if you have a standard installation).

- 2. A user-defined folder (which is what you want to store you personal #include files).

- 3. The script folder.

So how do you tell AutoIt where the user-defined folder is? Two ways to do it:

- 1. If you run the full SciTE4AutoIt3 package, you can use "SciTE Config" from the <Tools> menu to set the folder. (If you do not have the full package, then I recommend that you download it from here and install it. You get a load of goodies to help you code in AutoIt. ;) )

- 2. Or you can edit the registry directly (after taking the normal precautions, of course). As it says in the Help file:

There is a special registry value that can be created at "HKEY_CURRENT_USER\Software\AutoIt v3\AutoIt" called "Include". It should be a REG_SZ (string) value. The contents of this value are a semi-colon delimited list of directories that should be searched for files when resolving #include's in addition to the standard locations.

Once you have defined the user-defined folder, you just save .au3 files containing the functions that you want in that folder. Then when you need one of those functions, you can simply #include the relevant file. I would recommend that you do NOT put your own folder within the main AutoIt3 folder or it will get overwritten when you next upgrade. :shocked:

I hope that is all clear - ask if not. :)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

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...