How Can I Read Text From a File and Then Rename the File Using the Text I Just Read?

Guy! I would like to be able to open a file, read the first 10 characters, and then rename the file to those 10 characters plus a .txt file extension. How can I do that?

— KA

SpacerHey, Scripting Guy! AnswerScript Center

Hey, KA. Ah, for once a text file question that can be answered without some weird and convoluted workaround. This is actually pretty easy: we can use the FileSystemObject to open the text file and read in the first 10 characters, then use the FileSystemObject to rename the file to those 10 characters plus a .txt file extension. As you can see, all that takes just a few lines of code:

Const ForReading = 1

Set objFSO = CreateObject(“Scripting.FileSystemObject”)

Set objFile = objFSO.OpenTextFile(“C:\Scripts\Log.txt”, ForReading) strCharacters = objFile.Read(10) objFile.Close

strNewName = “C:\Scripts\” & strCharacters & “.txt”

objFSO.MoveFile “C:\Scripts\Log.txt”, strNewName

We begin by defining a constant named ForReading and assigning it the value 1; this constant is used when we open the text file for reading. We then create an instance of the FileSystemObject and use the OpenTextFile method to open the file C:\Scripts\Log.txt. With the file open we then read the first 10 characters and store that data on the variable strCharacters:

strCharacters = objFile.Read(10)

As you can see, we can use the Read method to read a specified number of characters from a text file. Suppose we wanted to read the first 37 characters from the file? No problem; we’d just use this line of code:

strCharacters = objFile.Read(37)

After closing the file we construct a new file name, one consisting of the folder path (C:\Scripts\), the 10 characters we just read in (represented by the variable strCharacters), and the new file extension (.txt). That, too requires just one line of code:

strNewName = “C:\Scripts\” & strCharacters & “.txt”

All that’s left is to rename the file. We can do that by using the FileSystemObject’s MoveFile method. (Don’t let the name fool you; in this case the file is simply being “moved” from its old name to its new name; it’s not changing locations within the file system). We pass MoveFile two parameters: the current path to the file, and the new path to the file. Sounds crazy, but “moving” a file within the same folder has the net effect of renaming it. Weird but true!


Comments are closed. Login to edit/delete your existing comments