File Operations – VBA, Python, VBS, C, C++ & DOS

It is important for any programming language to open text file or get data from external file or write to a external file. Without this open enabled in a programming language, it cannot be considered as a complete technology.

What do we offer here? – Simple Working Code Snippets – for quick reference

We have given code snippets, that quickly give the idea of how to open, read, write to a text file or a log file. We have covered these programming language code snippets for a quick reference.

What Programming Languages are Covered?

  1. Excel VBA Macro / VB
  2. VBS
  3. Python
  4. C
  5. C++
  6. DOS CMD Batch

Some Programming languages have more than one method to process text files. We have not presented all possible methods, but one method that would work good.

1. VBA Open Text File

The Visual Basic for Applications (VBA) code & VB6 code are one and the same in this case. Also, this VBA code can be used for importing data into Excel from text file or Outlook,Word etc.,

1. VBA Read From Text File

Public Sub VBA_Open_Text_File_Read()
    'Added  -
    Dim sFileNamePath As String, iFile As Double, sFileContent As String, sFileReadLine As String
    sFileNamePath = "D:/OutFile_Log.Txt"
    'Read All File Content to a String Variable
    iFile = FreeFile
    Open fname For Input As #iFile
        sFileContent = Input$(LOF(iFile), iFile)
    Close iFile
    'Read File Content Line by Line
    iFile = FreeFile
    Open fname For Input As #iFile
    Do While Not EOF(iFile)
        Line Input #iFile, sFileReadLine
    Close iFile
End Sub

2. VBA Write To Text File

Use this VBA or VB6 code to write data to a text file.

Public Sub VBA_Write_To_Text_File(sOptAppend As String, Optional fMsg As String)
    'Added  -
    Dim sFileNamePath As String, iFile As Double
    sFileNamePath = "D:/OutFile_Log.Txt"
    'Get Number To handle File
    iFile = FreeFile
    'Open Text File in Append or Output Mode
    If sOptAppend = "A" Then
        Open sFileNamePath For Append As #iFile
        Open sFileNamePath For Output As #iFile
    End If
    'Use Write or Print Command to Write To File
    Print #iFile, fMsg 'Write Data without any formatting
    Write #iFile, fMsg 'WRite data with automatic Quotes & delimiters
    'To Print Data on Same line, add a Comma at end of Print or Write Statement
    Print #iFile, fMsg,
    Print #iFile, fMsg
    'Close the File using FileNumber
    Close iFile
End Sub

For any of the Microsoft Office Applications, the code snippet can be used in the VB editor (Press Alt + F11 to invoke VB Editor from any MS Office Application)

2. VBScript (VBS) – Write To Text File

The ‘Open Filepath For Output/Input/Append as #fNum” command use in the above example will not work in VBScript. We have to use the Scripting.Filesystemobject to perform this operation within VBS file.

But, this code snippet will also work in a VBA code with no modifications.

Public Sub VBScript_Open_Text_File_Write_Read()
    'Added  -
    Dim sFileNamePath As String, sFileContent As String, sFileReadLine As String
    sFileNamePath = "D:/OutFile_Log.Txt"

    Dim oFSO As Object, oFile As Object, iTextStream As Object
    Set oFSO = CreateObject("Scripting.FileSystemObject")
    'Write to Output Text File
    Set oFile = oFSO.CreateTextFile(sFileNamePath, True)
        oFile.WriteLine "Write Data to Text File1"
        oFile.WriteLine "Write Data to Text File2"
        oFile.WriteLine "Write Data to Text File3"
    'Read/Import from Text File
    Set iTextStream = oFSO.OpenTextFile(sFileNamePath, 1)
        MsgBox iTextStream.Read(10) 'Read Number of Charcters
        MsgBox iTextStream.ReadLine 'Read Line by Line - From Characters read in Previous Command
        MsgBox iTextStream.ReadLine
        MsgBox iTextStream.ReadAll  'Read Full Text File Content
    'Garbage Collection - Disconnect All Allocated Objects
    Set iTextStream = Nothing
    Set oFile = Nothing
    Set oFSO = Nothing
End Sub

3. Python Open, Read, Write To Text File

This seems very easy as similar to VBA. Actually I learnt it only while preparing this article. Nice to learn new tech on the go.

#Python Write to Text File
f = open('d:/helloworld.txt','w')
f.write('hello world1\n')
f.write('hello world2\n')
f.write('hello world3' + '\n')
f.write('hello world4')

#Read from Text File
f = open('d:/helloworld.txt','r')
fText =

#Read Text File Character by Character
fText =
while fText != "":
    fText =

#Read Text File Lines
fText = f.readline(7)
fText = f.readlines()

#Close File

4. C Program File Operation Commands

Here is the simplest C code that can read characters from a input file & write it to another file. One file is opened in read mode & another in Write mode. Another file operation possible is append mode “a”.

Apart from this, there are three more possible file operation mode r+, w+ & a+. when you put a ‘+’ symbol in front of a mode it means that it is compatible to perform the other 2 modes as well.

For example, if it is ‘r+’ – it means that it can also be used to read, write & append to that file.

/* Read Input File Character By character & Write to Another file */
/* Copy content from One file to Another Text file*/
# include "stdio.h"
main ()
	FILE *ifp, *ofp;
	char fch;
	/*Open File in Read mode*/
	ifp = fopen ("ifile.txt","r");
	ofp = fopen ("ofile.txt","w");
	while (1)
		/*Read Character by Character*/
		fch = fgetc(fp);
		/*Check for End of File*/
		if (fch == EOF)
		/*Write to Output File*/
	/*Close File*/

5. C++ to Open Text File

/*Read & Write to File using C++ code -*/
#include <iostream>
#include <fstream>
using namespace std;

int main()
{	/*Declare variable used in the program*/
	char fstr[200];
	char fch;
	fstream iofile;
	/*Open the file in IO Mode*/ ("iofile.txt", ios::out | ios::in );

	/*Assign Some Text to a String variable*/
	cout << "Hello World - File Operations - Read & Write" << endl;
	cin.getline(fstr, sizeof(fstr));
	/*Writing String to the File*/
	iofile << fstr << endl;

	/*Reading the String from Same file*/
	iofile >> fstr;
	cout << fstr << endl;
	/*Read Character by Character till End of File
		if (iofile.eof())
		std::cout << fch;
	/*close iofile*/
	return 0;

6. Command Prompt DOS Batch

We don’t have much flexibility in DOS. But still it is very easy way to automate few tiny things using a DOS Batch. Here is not to write & read from a text file.

@echo off
echo 123>textfile.txt
echo "abc">>textfile.txt
type textfile.txt
more textfile.txt

Hope you like this article. If you have any programming languages that would interest you, please leave a simple comment. I will make sure that the required code gets added to this page.

Leave a Reply