By using this site you agree to the use of cookies by Brugbart and our partners.

Learn more

Write Content to a File with AutoIt

Creating files and write content to the files using AutoIt.

Edited: 2015-02-13 00:26

Last Tutorial: Read files with AutoIt

AutoIt Logo

When you want to create a file with AutoIt, you do not really need to think about creating it – files are automatically created if they do not already exist. When you use the FileOpen function to open a file in write mode, the file will automatically be created if it does not already exist.

How data is written to a file, is controlled with the FileOpen function, the last parameter controls how the data is written to the file. A value of "1" will append the data to the end of the file, while a value of "2" will overwrite the file – read the reference for more information on FileOpen.

Writing to a file with AutoIt

The below example writes a couple of lines to the end of a text file, test.txt.

$file = FileOpen("test.txt", 1)

FileWrite($file, "Line1")
FileWrite($file, "Still Line1" & @CRLF) ; The CRLF at the end is a line break
FileWrite($file, "Line2")

FileClose($file)

It can sometimes be a good idea to first check if the file was opened for writing, this can be done by checking the return value of FileOpen. I.e. If it failed, or if it successfully opened the file.

$file = FileOpen("test.txt", 1)

If $file = -1 Then
  MsgBox(0, "Error", "Unable to open file.")
Else
  FileWrite($file, "Line1")
  FileWrite($file, "Still Line1" & @CRLF) ; The CRLF at the end is a line break
  FileWrite($file, "Line2")
  FileClose($file)
EndIf

FileOpen can fail due to access rights, etc.. Usually not a problem.

If you already have a variable filled with content, including line breaks, etc. Just do like below:

$sMyContent = 'Test content
more test
and some more test.'

$file = FileOpen("test.txt", 1)

FileWrite($file, $sMyContent)
FileClose($file)