Jump to content

Write or append to .txt file


RaySS
 Share

Recommended Posts

How to create and then write, read, or append to a text file?

I tried to adapt the snippet by guinness as follows:

#include <File.au3>
Local $sOutPath = "D:\Temp\"
_FileCreateEx(@ScriptDir & '\ExampleFile.txt', 42)


; Create a blank file with a certain size in bytes.
Func _FileCreateEx($sFilePath, $iBytes = 0)
    ConsoleWrite("Look in: " & $sFilePath & @CRLF)
    Return RunWait(@ComSpec & ' /c fsutil file createnew "' & $sFilePath & '" ' & Int($iBytes), $sOutPath, @SW_HIDE)
    Sleep(10000)
EndFunc   ;==>_FileCreateEx

1. The .txt file is being created in the folder where I store AutoIT examples  --  not in D:\Temp\ as expected.

2. In an attempt to see the result of running the function, I tried using the @SW_SHOW option with a 5 second sleep in the next statement. The CMD window didn't stay open for five seconds. It just flashed momentarily.

3. The file contains unprintable binary characters. I didn't see a way to write, read, or append strings or numbers or arrays to the file. Help shows File I/O for .INT files only.

4. The fsutil function is much too powerful for this task. Faulty use of fsutil could alter a disk's partition table or do other drastic  feats. I didn't see a good tutorial on file I/O.

Thank you for your help.

RaySS

Link to comment
Share on other sites

If I understand you right, then you are making this much more complex than it needs to be.

@ComSpec, which you don't really need, will write to the default working directory, whatever that is, unless you specify otherwise.

Checkout the FileOpen, FileClose, FileRead, FileWrite, etc commands. You can use them along with _FileCreate if you wish, though it isn't needed.

Make sure brain is in gear before opening mouth!
Remember, what is not said, can be just as important as what is said.

Spoiler

What is the Secret Key? Life is like a Donut

If I put effort into communication, I expect you to read properly & fully, or just not comment.
Ignoring those who try to divert conversation with irrelevancies.
If I'm intent on insulting you or being rude, I will be obvious, not ambiguous about it.
I'm only big and bad, to those who have an over-active imagination.

I may have the Artistic Liesense ;) to disagree with you. TheSaint's Toolbox (be advised many downloads are not working due to ISP screwup with my storage)

userbar.png

Link to comment
Share on other sites

  • Moderators

RaySS,

You do like making the simple complex:

#include <FileConstants.au3>
#include <MsgBoxConstants.au3>

; Create file in same folder as script
$sFileName = @ScriptDir &"\Test.txt"

; Open file - deleting any existing content
$hFilehandle = FileOpen($sFileName, $FO_OVERWRITE)

; Prove it exists
If FileExists($sFileName) Then
    MsgBox($MB_SYSTEMMODAL, "File", "Exists")
Else
    MsgBox($MB_SYSTEMMODAL, "File", "Does not exist")
EndIf



; Write a line
FileWrite($hFilehandle, "This is line 1")

; Read it
MsgBox($MB_SYSTEMMODAL, "File Content", FileRead($sFileName))

; Append a line
FileWrite($hFilehandle, @CRLF & "Thisi is line 2")

; read it
MsgBox($MB_SYSTEMMODAL, "File Content", FileRead($sFileName))

; Close the file handle
FileClose($hFilehandle)

; Tidy up by deleting the file
FileDelete($sFileName)

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

Hi Santa and M23,

Thank you both for replying.

@M23

Your example should be posted among the snippets. It would have saved me a frustrating morning of searching through Help and on Google only to come up with the fsutil solution.

Again, thank you both.

RaySS

Link to comment
Share on other sites

  • Moderators

RaySS,

That script is essentially the Help file example for FileWrite - I think you need to read both the function description and the examples a little more carefully rather than go searching for esoteric solutions. Remember AutoIt is designed to be easy to use, so if you only find a complex solution for a relatively simple matter such as writing to a text file there is probably a simpler answer as well.

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

  • 6 years later...

A simplistic example of a function that writes a line of text to the log whenever called:

#include <date.au3>
Func _WriteDateOfDataReviewToLog($sFileName)

   local $sWriteOption
   If FileExists($sFileName) Then
      $sWriteOption = $FO_APPEND
   Else
      $sWriteOption = $FO_OVERWRITE
   EndIf

   Local $hFilehandle = FileOpen($sFileName, $sWriteOption)
   Local $sLogEntry = _Now() & " - Writing line of text with date to log file" & @CRLF
   FileWrite($hFilehandle, $sLogEntry)
   FileClose($hFilehandle)

EndFunc

 

Edited by NYCmitch25
Link to comment
Share on other sites

  • 4 months later...

that one 

 

 
#include <date.au3>
Func _WriteDateOfDataReviewToLog($sFileName)

   local $sWriteOption
   If FileExists($sFileName) Then
      $sWriteOption = $FO_APPEND
   Else
      $sWriteOption = $FO_OVERWRITE
   EndIf

   Local $hFilehandle = FileOpen($sFileName, $sWriteOption)
   Local $sLogEntry = _Now() & " - Writing line of text with date to log file" & @CRLF
   FileWrite($hFilehandle, $sLogEntry)
   FileClose($hFilehandle)

EndFunc
 

 

Edited by hoguz2
Link to comment
Share on other sites

  • Developers

As stayed already:  that posted script doesn't do anything as posted

you need to use that udf in your own script!

Edited by Jos

SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource   Forum etiquette  Forum Rules 
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Link to comment
Share on other sites

#include <MsgBoxConstants.au3>

#include <Array.au3>

HotKeySet('Q', 'EndProgram')
HotKeySet('{ESC}', 'ExitProgram')
Func EndProgram()
    Exit
EndFunc   ;==>EndProgram
Func ExitProgram()
    Exit
EndFunc   ;==>ExitProgram

_goto()

Func _goto()


Local $iCheckSum = PixelChecksum(504,91,578,102)


    While $iCheckSum = PixelChecksum(504,91,578,102)
        Sleep(100)

    WEnd

    MsgBox($MB_SYSTEMMODAL, "", "MESSAGE!")

; here I need the code to log the date , hour , minute in a .txt file line by line. Can you help me ?

    _goto()


EndFunc

 

Edited by hoguz2
Link to comment
Share on other sites

Hi @hoguz2,

in case I understood you correct, this should be fit your requirements:

#AutoIt3Wrapper_AU3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6 -w 7
#AutoIt3Wrapper_AU3Check_Stop_OnWarning=y
#AutoIt3Wrapper_Run_Au3Stripper=y
#AutoIt3Wrapper_UseUpx=n
#Au3Stripper_Parameters=/sf /sv /mo /rm /rsln

#include-once
#include <Date.au3>

HotKeySet('{ESC}', '_Exit')

While True
    _LogPixelChecksumChange()
    Sleep(250)
WEnd

Func _Exit()
    Exit
EndFunc

Func _WriteDateOfDataReviewToLog($sFileName)
   Local $sWriteOption

   If FileExists($sFileName) Then
      $sWriteOption = $FO_APPEND
   Else
      $sWriteOption = $FO_OVERWRITE
   EndIf

   Local $hFilehandle = FileOpen($sFileName, $sWriteOption)
   Local $sLogEntry = _Now() & ' - Writing line of text with date to log file' & @CRLF

   FileWrite($hFilehandle, $sLogEntry)
   FileClose($hFilehandle)
EndFunc

Func _LogPixelChecksumChange()
    Local Const $iLeft   = 504
    Local Const $iTop    = 91
    Local Const $iRight  = 578
    Local Const $iBottom = 102

    Local Const $iCheckSum = PixelChecksum($iLeft, $iTop, $iRight, $iBottom)

    While ($iCheckSum == PixelChecksum($iLeft, $iTop, $iRight, $iBottom))
        Sleep(100)
    WEnd

    MsgBox($MB_SYSTEMMODAL, "", "MESSAGE!")

    Local Const $sTargetFile = @ScriptDir & '\log.txt'

    _WriteDateOfDataReviewToLog($sTargetFile)
EndFunc

It is basically the function of @NYCmitch25 in combination with your PixelChecksum(). Each time the checksum changes, you will receive a message and after that the log entry will be written. The program will run until you press ESC.

The result will look like this:
image.png.3b75caf8e6e791b1edb81f7f8c2947b3.png

Is that what you're looking for?

Best regards
Sven

Edited by SOLVE-SMART

Stay innovative!

Spoiler

🌍 Au3Forums

🎲 AutoIt (en) Cheat Sheet

📊 AutoIt limits/defaults

💎 Code Katas: [...] (comming soon)

🎭 Collection of GitHub users with AutoIt projects

🐞 False-Positives

🔮 Me on GitHub

💬 Opinion about new forum sub category

📑 UDF wiki list

✂ VSCode-AutoItSnippets

📑 WebDriver FAQs

👨‍🏫 WebDriver Tutorial (coming soon)

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