Many a times you may need to interact with text files using QTP. Interaction can be(but not limited to) in the form of reading input from a file, writing output to a file. This post describe in detail “File handling using QTP”.
We use FSO object to do this.
What is FSO?
FSO stands for File System Object. This is used to support text file creation and manipulation through the TextStream object and is contained in the Scripting type library (Scrrun.dll)
The FSO Object Model has a rich set of properties, methods and events to process folders and files.
How to create a file?
We first create a FSO object using CreateObject and then create a text file using CreateTextFile.
For Example: Suppose you want to create a file called “test.txt” located in C:
Dim fso, file, file_location
file_location = “C:file_location”
Set fso = CreateObject(“Scripting.FileSystemObject”)
Set file = fso.CreateTextFile(file_location, True) // True–> file is to be overwritten if it already exists else false
We would use the same example for the rest of this post.
How to open a file?
Set file= fso.OpenTextFile(“C:file_location”, ForWriting, True)
//2nd argument can be ForReading, ForWriting, ForAppending
//3rd argument is “True” if new file has to be created if the specified file doesn’t exist else false, blank signify false.
How to read content from a file?
Use ReadLine() method
For example:
Set file= fso.OpenTextFile(“C:file_location”, ForReading, True) //2nd argument should always be “ForReading” in order to read contents from a file
Do while file.AtEndofStream <> True
data = file.ReadLine()
msgbox data
Loop
How to write content to a file?
You can use Write() or WriteLine() Methods to write text into a file. The difference between the Write() and WriteLine() Method is that the latter automatically inserts a new line character while the former doesn’t insert a new line character.
For example:
Set file= fso.OpenTextFile(“C:file_location”, ForWriting, True) //2nd argument should always be “ForWriting” in order to write contents to a file
file.Write(“This is a place to get all your qtp”)
file.Write(“questions and answers solved.”)
//Output will be:
This is a place to get all your qtp questions and answers solved.
while
file.WriteLine(“This is a place to get all your qtp”)
file.Write(“questions and answers solved.”)
//Output will be:
This is a place to get all your qtp
questions and answers solved.
How to delete content?
Use DeleteFile() method to delete a file from a particular location
Foe Example:
file_location = “C:file_location”
Set fso = CreateObject(“Scripting.FileSystemObject”)
fso.DeleteFile(file_location)
If you want to keep track of further articles on QTP. I recommend you to subscribe via RSS Feed. You can also subscribe by Email and have new QTP articles sent directly to your inbox.
How to write a file which I captured from webedit?
Ex – startTime=Browser(“Welcome to QTPXXXXX”).Page(“PT – Service Request_12”).WebEdit(“Target Start:”).GetROProperty(“value”)
I have captured start time and i want to write into a txt file
Hi I am new to qtp and vb script, Please tell me how to find a particular name in an .txt file and if the name exists then, take that name from txt file and place in available space in excel?
Set objFSO = CreateObject(“Scripting.FileSystemObject”)
Set objFile =objFSO.OpenTextFile(“U:\MyDocuments\myTextFile.Txt”, 1)
Do Until objFile.AtEndOfStream
strNextLine = objFile.ReadLine
If Instr(strNextLine,”required name”)>0 Then
‘Do required thing here
End If
Loop
want to change file name with every loop for Const XMLDataFile
for example
Const XMLDataFile =”C:\sitemap\” &s
s is variable and storing file name using loop
pls tell me how to pass it to Const XMLDataFile.
pls help me
compare data wordpad to wordpad using File system objects.I need code for this.It will be helpful for me if u can post me with a reply on this asap.
Thanks,
Rajesh P.
Hi…
I have a lot of PDF files in a folder.How to read all the file names with extention “.pdf” and place them in an excel sheet???
Hi Ankur,
Please let me know how to read from a text file the CSV values into the QTP with a condition that, it should read the lines that start after the line’s that start with a ‘#’.
ex : mytext.txt contains :
#TestCase01
Yes,No
#TestCase02
True,False
now I want to pass Yes and No as parameters under ‘#TestCase01’ and True and False as arameters under “#TestCAse02” and can use lines that start with # as only condition and am considering these lines as commented out lines.
Hi Ankit,
Thank you for sharing the knowledge.Could you please inform what is the objectname for creating UFT.
Like in QTP 11.0, we use
set qtapp=createobject(“QuickTest.Application”).
In QTP 11.0 we use “QuickTest.Application” What do we use in UFT 11.5?
Regards,
Jaya
@Jaya: It should be same.
Hi,
Could U tell how to count number of words in a text file
Waiting for ur reply
Thankyou
This might work:
data = file.readline()
datalength = len(Trim(data))
Hi I am using this Code , Taking textfrom PDF and trying to put it in Note Pad, The text i am getting in variable TextStr has the Length of 47050 is that the huge .??
Const ForReading = 1, ForWriting = 2
Dim oPDF,fso, f
Set oPDF=createobject(“LearnQuickTest.ManipulatePDF”)
Pdftext= oPDF.GetPdfText(“C:\Documents and Settings\c91701ju\Desktop\TestPdf\COB 14597.pdf”)
TextStr=cstr(Pdftext)
Set fso = CreateObject(“Scripting.FileSystemObject”)
Set f = fso.OpenTextFile(“C:\Documents and Settings\c91701ju\Desktop\TestPdf\Diffrence.txt”,2,True)
f.Write TextStr — I tried WriteLine also same format as in QTP help but its not working. Always getting error
Invalid Procedure call or Arguement
if i try just redaing the Leghth
f.Write len(TextStr) this working fine, but i need the text not the lenght can any one help me on this
@Ahmed: It would be great if you can ask your question on QTP forums.
Very good explanation in a simple way on file handling! Your site is very helpful for learning & refreshing concepts on QTP. thanks a lot! Keep up the good work..
I need to search a text in a file.
In the below text file i need to search the value 100 at the top and add values 20+20+20+20+20 and validate if that total is equal to the 100 on top of the text file.
ex: abc.txt
=======================
total records = 100 (this can change)
break down:
A=20(these values can change)
b=20
c=20
d=20
e=20
Total=100
=======================
I have the below requirement
In our application if the user registers, password will be sent to email. We have to open the email, capture/read the password and should login to the application with the generated password.
I got the code to open an email and display the content in the email. But dont know how to capture the password from the email.Please help me on this. Below is the code used for reading an email
Set olApp=createObject(“outlook.Application”)
Set olns=olApp.GetNameSpace(“MAPI”)
Set objFolder=olns.GetDefaultFolder(6)
‘Set item1=
For each item1 in objFolder.Items
If item1.unread and item1.subject=”User registration” Then
msgbox item1.body
End If
Next
‘–Script to create a number of file with content similar to file name.—
‘———————————————————————
Option Explicit
Dim NumberOfFiles, fcntr
Dim baseString
Dim content, fileName
Dim testFolder
NumberOfFiles = 100
testFolder = “C:\FileTest\”
baseString = “qtp_datfile”
FOR fcntr = 1 to NumberOfFiles
fileName = testFolder & baseString & fcntr & “.dat”
content = baseString & fcntr
createfile fileName,content
NEXT
Function createfile (fname, strwrite)
Dim fso , ftext
Set fso = createObject(“Scripting.FileSystemObject”)
Set ftext = fso.OpenTextFile(fname,8,True)
ftext.writeline(strwrite)
ftext.close
End Function
I have a Unique requirement:
I have collected function_name, data(parm) from datasheet and concatenated them in a string .
now I want to use this string to execute respective functions with params .. Any help?
E.g.:
set_text&” “¶m1&”,”¶m2
i want to create .dat file with file name as the innertext i.e if qtp_datfile1.dat is the file and qtp_datfile1 as the innertext.i want to create 100 files like this with file name changes like qtp_datfile1,qtp_datfile2…..anybody pls help
Hi Ankur,
Thanks for sharing such great information, its really very useful.
one quick question: is it possible to compare excel shet value with notepad file, if yes please provide details.
Thnaks in advance.
Sub OpenTextFileTest
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim fso, f
Set fso = CreateObject(“Scripting.FileSystemObject”)
Set f = fso.OpenTextFile(“c:\testfile.txt”, ForWriting, True)
f.Write “Hello world!”
f.Close
End Sub
WORKS!
Thanks for the info Ankur.Very clearly said and in a organised way,this is i feel..:-)
hi… am very happy that am getting to learn many things in QTP:):):)
Very clear. I found all I needed in this short and clear post. Thank you!
Can anybody tell me how can I open a file in one script and write into it in a different script?
Ankur – You’re awesome. Thanks for these tips. I needed this explanation and it really helped me when I needed it most.
Thanks again!
I am new to QTP and can anyone please tell of how to count the number of lines in a test.
I have a test, in which many actions are there.
So i need the number of lines, seperately for each action and the whole one for the Test.
Can you help me out?
SUB to add a line to a file —
Addaline “C:ScriptsVB_Codetestfile.txt”, “This is the line to be added”
SUB Addaline(filename, lineToAdd)
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim fso, freader, textstr, wcount
SET fso = CreateObject(“Scripting.FileSystemObject”)
SET freader = fso.OpenTextFile(filename, ForAppending)
freader.Writeline(lineToAdd) ‘This can be cahnged to Write if you want no newline in the end
freader.close
END SUB
Above script for wordcount needs to be corrected, as we are counting the number of spaces and getting the upper bound of the array. Which will resul in 2 words less than the actual. So the corrected script is below
——————————
Dim wcnt
wcnt = getWordCount(“C:ScriptsVB_Codetestfile.txt”)
msgbox “Total number of words in your file is ” & wcnt
FUNCTION getWordCount(filename)
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim fso, freader, textstr, wcount
SET fso = CreateObject(“Scripting.FileSystemObject”)
SET freader = fso.OpenTextFile(filename, ForReading)
textstr = freader.ReadAll()
freader.close
getWordCount = UBound(split(textstr, ” “, -1)) + 2
END FUNCTION
Script to find wordcount
Dim wcnt
wcnt = getWordCount(“C:\Scripts\VB_Code\testfile.txt”)
msgbox “Total number of words in your file is ” & wcnt
FUNCTION getWordCount(filename)
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Dim fso, freader, textstr, wcount
SET fso = CreateObject(“Scripting.FileSystemObject”)
SET freader = fso.OpenTextFile(filename, ForReading)
textstr = freader.ReadAll()
freader.close
getWordCount = UBound(split(textstr, ” “, -1))
END FUNCTION
hi,
i have a question because i am new to qtp.
i wrote a function which writes string to the file which is open in append mode.
Now when i am to passing the values to that function, it is not writing into the file.
can anyone of you guys can show me a sample code for that ?
Hi Ankur,
How can i find or count the word present in Text File
Put double quotes around the argument and it will work. ==> Set fso = CreateObject (“Scripting.FileSystemObject”)
HI Ankur,
it is really helpfull.
i have a problem, that in my script,
it is giving a run error
object required: ‘Scripting’
Line () : “Set fso = CreateObject (Scripting.FileSystemObject)”
can you help me.
Hi All
i have one question in my mind
QTP uses Compiler or Interpreter ?
if it uses Compiler, then what its name?
Problem :-
I am getting following error
Invalid procedure call or argument
Line (12): “Set file= fso.OpenTextFile(“C:text.txt”, ForReading, True)”.
Do I need to add Scrrun.dll lidrary. If yes then please guide me how to do that..?
Solution:
just write this code
Set file= fso.OpenTextFile(“C:text.txt”)
it will work.
hello .. i m new to QTP anywy..i saw the article.. nice one …i can extract it as..
File handling with QTP
Create filesystem object:
Set fso = CreateObject(“Scripting.FileSystemObject”)
//Way to create a file.. override it “True”, not “False”
Set file = fso.CreateTextFile(file_location, True)
//Open text file for writing
Set file= fso.OpenTextFile(“C:file_location”, ForWriting, True)
//open text file for reading
Set file= fso.OpenTextFile(“C:file_location”, ForReading, True)
//Read file data
Do while file.AtEndofStream <> True
data = file.ReadLine()
msgbox data
Loop
//Write data to file
file.Write(“questions and answers solved.”)
//Delete file
fso.DeleteFile(file_location)
//Create a folder
Set fso1 = fso.createfolder(“C:FolderFolder1”)
Here we are not closing the file ..like we does it in c#….
is it expected ???
I am getting following error
Invalid procedure call or argument
Line (12): “Set file= fso.OpenTextFile(“C:text.txt”, ForReading, True)”.
Do I need to add Scrrun.dll lidrary. If yes then please guide me how to do that..?
Hi Ankur,
1. how can I compare two text file
2. can I open an excel file using filesystemobject
Hi All,
I want to replace a complete line
after comparing the line with subsection of line
any solution pplease mail it to teja431@gmail.com
hi all,
I have a requirement where log file is generated and from that log file i need to get the content and save in another logfile through file object how can it be done?
Hello,
Very nice explanation.
Just one question: how to paste data into a text file ?
hey
its working now .. i was copy pasting the stuff from the browser n QTP wasnt accepting the double quotes properly (“)
thanks
hey
this is what I get when I try to run the first step :
Dim fso, file1, file_location
file_location = “C:\test.txt”
Set fso = CreateObject(“Scripting.FileSystemObject”)
Set file1 = fso.CreateTextFile(file_location, True)
in QTP 10:
The test run cannot continue due to a syntax error.
Invalid character
Line (1): “Set fso = CreateObject(“Scripting.FileSystemObject”)”.
it would be great if someone could point out whats going wrong
Hi you can create subfolder within folder by using following code:
Set fso = CreateObject(“Scripting.FileSystemObject”)
fso.createfolder(“C:Folder”) ‘create a folder
Set fso1 = fso.createfolder(“C:FolderFolder1”) ‘ Create subfolder within main folder
For more information please fo through http://msdn.microsoft.com/en-us/library/ebkhfaaz(VS.85).aspx
Cheers
hi ankur,
i have another prob in fso..
1) how to create sub folder under folder
D:\folder\folder1\folder2
D:\folder\file
2) how to access those sub folders.or files
kindly reply fast..
Thanks..
very helpful solution to handle files using QTP
i have problem read a txt file, which is generated as a log file for our S/W produce. The default location of the file is location ‘C:Documents and SettingsAll UsersApplication DataSTRAQ.DirectorLogs’. The default name of the file is xxxx.xxxx.xxxx.txt
i have tried reading the file after renaming the file ( say xxxx.txt), it did not work
i have tried changing the location of the file, it did not work
It works only when i copy the content of the file to any other txt file
Please suggest any solution
very helpful solution to handle files using QTP
i have problem reading content from file.
We have a S/W product which generates a log file in txt format and stores by default at ‘location ‘C:Documents and SettingsAll UsersApplication DataSTRAQ.DirectorLogs’. The name of the log file is something like xxxxx.xxxxx.xxxx.txt.
I have used FSO and also SystemUtil.Run methods to open the file and read the content of the file. But, could not . i tried after renaming the file with a simple name (xxxx.txt), it did not work.
It doesn’t work, when i change the location of the file
It works only when i copy the content of the file to any other txt file.
Please suggest any solution
Can i read and write in one shot means reading from one file and writing it in another file by creating the other new file
Hi, Ankur
The info regards FSO is very much understandable. Explnation which you have given for each functions are harmony…
thanks Brother.
—- ganesh
Hi Ankur,
this information is really valuable and organised!!!
Hi Ankur..this is very good information provided and in very organised manner..