Open Text File – Read Write File Operations – VBA, Python, VBS, C, C++, DOS

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 Kumarapush123@gmail.com  - https://officetricks.com
    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
    Loop
    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 Kumarapush123@gmail.com  - https://officetricks.com
    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
    Else
        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 Kumarapush123@gmail.com  - https://officetricks.com
    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"
    oFile.Close
    
    '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
    iTextStream.Close
    
    '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')
f.close()

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

#Read Text File Character by Character
f.seek(0)
fText = f.read(2)
while fText != "":
    print(fText)
    fText = f.read(1)

#Read Text File Lines
f.seek(0)
fText = f.readline(7)
print(fText)

f.seek(0)
fText = f.readlines()
print(fText)

#Close File
f.close()

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)
			break;
		printf("%c",fch);
		
		/*Write to Output File*/
		fputc(fch,ofp);
	}
	
	/*Close File*/
	fclose(ofp);
	fclose(ifp);
}

5. C++ to Open Text File

/*Read & Write to File using C++ code - Officetricks.com*/
#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.open ("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
	while(1)
	{
		iofile.get(fch);
		if (iofile.eof())
			break;
		std::cout << fch;
	}
	
	/*close iofile*/
	iofile.close();
	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
cls
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