지정된 파일을 열고 파일에서 읽기, 쓰기 또는 파일에 추가하는 데 사용할 수 있는 TextStream 객체를 반환합니다.
구문
object.OpenTextFile(filename[, iomode[, create]])
인수:
FileSystemObject의 이름입니다.Format: 선택사항. 열린 파일의 형식을 나타냅니다.
주:
Format 인수는 휴면 상태이며 VB 스크립트 구문을 모방하기 위해 유지됩니다. 아무런 기능도 하지 않습니다. 생성되는 모든 파일은 Unicode 형식으로만 표시됩니다.
설정
iomode 인수는 다음 설정을 포함할 수 있습니다.
표 11-34 IOMode 인수 설정
| 상수 | 값 | 설명 |
|---|---|---|
| ForReading | 1 | 읽을 파일만 엽니다. 이 파일에는 쓸 수 없습니다. |
| ForWriting | 2 | 파일을 열어 쓰기 작업을 수행합니다. |
| ForWriting | 8 | 파일을 열고 파일의 끝에 씁니다. |
주석
다음 코드는 OpenTextFile 메소드의 사용을 보여줍니다.
주:
New File이 생성되면 Unicode 형식으로 생성됩니다.
File이 없는 경우 코드는 ReadMode에서 오류를 throw합니다.
예 1:
Sub OpenFileForReading()
Const ForReading = 1
Dim fso, tso
Set fso = CreateObject("Scripting.FileSystemObject")
Set tso = fso.OpenTextFile("C:\example1.txt", ForReading)
tso.Close ' Close the file.
Set tso = Nothing
Set fso = Nothing
End Sub
Call OpenFileForReading
'If C:\example1.txt is not present then code will throw an error.
예 2:
Sub OpenFileForWriting()
Const ForWriting = 2
Dim fso, file
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("C:\example2.txt", ForWriting, True)
file.WriteLine("This is written to the file.") ' Writes text to the file.
file.Close ' Close the file.
Set file = Nothing
Set fso = Nothing
End Sub
Call OpenFileForWriting
'Creates C:\example2.txt and writes a line "This is written to the file."
예 3:
Sub OpenFileForAppending()
Const ForAppending = 8
Dim fso, file
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("C:\example2.txt", ForAppending, True)
file.WriteLine("This line is appended.") ' Appends text to the file.
file.Close ' Close the file.
Set file = Nothing
Set fso = Nothing
End Sub
Call OpenFileForAppending
'Creates C:\example2.txt and writes a line "This line is appended.". If file already exists it appends this line.
예 4:
Sub OpenFileWithCreateOption()
Const ForWriting = 2
Dim fso, file
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.OpenTextFile("C:\example2.txt", ForWriting, True) ' Creates the file if it doesn't exist.
file.WriteLine("New File created and text written.") ' Writes text to the file.
file.Close ' Close the file.
Set file = Nothing
Set fso = Nothing
End Sub
Call OpenFileWithCreateOption
'Overwrites C:\example2.txt and writes a line "New File created and text written.". If file does not exists then it creates it.