- Метод OpenTextFile OpenTextFile method
- Синтаксис Syntax
- Параметры Settings
- Примечания Remarks
- См. также See also
- Поддержка и обратная связь Support and feedback
- What Is a Text File?
- How to open, edit, and convert text files
- Types of Text Files
- How to Open a Text File
- Open Any File as a Text Document
- How to Convert Text Files
- Is Your File Still Not Opening?
- Open text file and program shortcut in a Windows batch file
- 12 Answers 12
Метод OpenTextFile OpenTextFile method
Открывает указанный файл и возвращает объект TextStream , который можно использовать для чтения, записи в файл или добавления в него. Opens a specified file and returns a TextStream object that can be used to read from, write to, or append to the file.
Синтаксис Syntax
объект. OpenTextFile (filename, [ iomode, [ CREATE, [ Format ]]]) object.OpenTextFile (filename, [ iomode, [ create, [ format ]]])
Синтаксис метода OpenTextFile состоит из следующих элементов. The OpenTextFile method has these parts:
Часть Part | Описание Description |
---|---|
object object | Обязательный. Required. Всегда является именем объекта FileSystemObject. Always the name of a FileSystemObject. |
задан filename | Обязательный. Required. Строковое выражение, определяющее файл, который будет открыт. String expression that identifies the file to open. |
iomode iomode | Необязательно. Optional. Указывает режим ввода-вывода. Indicates input/output mode. Может соответствовать одной из трех констант: ForReading, ForWriting или ForAppending. Can be one of three constants: ForReading, ForWriting, or ForAppending. |
создать create | Необязательно. Optional. Значение типа Boolean, которое указывает, можно ли создать новый файл, если файл, указанный параметром filename, не существует. Boolean value that indicates whether a new file can be created if the specified filename doesn’t exist. Значение True позволяет создать новый файл, а значение False — нет. The value is True if a new file is created; False if it isn’t created. По умолчанию используется значение False. The default is False. |
format format | Необязательно. Optional. Одно из трех значений Tristate, используемых, чтобы указать формат открытого файла. One of three Tristate values used to indicate the format of the opened file. Если отсутствует, открытый файл имеет формат ASCII. If omitted, the file is opened as ASCII. |
Параметры Settings
Аргумент iomode может иметь любой из следующих параметров: The iomode argument can have any of the following settings:
Константа Constant | Значение Value | Описание Description |
---|---|---|
форреадинг ForReading | 1,1 1 | Открытие файла только для чтения. Open a file for reading only. Запись в этот файл невозможна. You can’t write to this file. |
форвритинг ForWriting | 2 2 | Открывает файл только для записи. Open a file for writing only. Используйте этот режим для замены существующего файла новыми данными. Use this mode to replace an existing file with new data. Не удается выполнить чтение из этого файла. You can’t read from this file. |
фораппендинг ForAppending | 8 8 | Открытие файла и запись в конец файла. Open a file and write to the end of the file. Не удается выполнить чтение из этого файла. You can’t read from this file. |
Аргумент format может иметь одно из следующих значений. The format argument can have any of the following settings:
Константа Constant | Значение Value | Описание Description |
---|---|---|
тристатеуседефаулт TristateUseDefault | –2 -2 | Открывает файл с использованием системы по умолчанию. Opens the file by using the system default. |
тристатетруе TristateTrue | –1 -1 | Открывает файл в формате Юникод. Opens the file as Unicode. |
тристатефалсе TristateFalse | нуль 0 | Открывает файл в формате ASCII. Opens the file as ASCII. |
Примечания Remarks
В следующем коде показано использование метода OpenTextFile для открытия файла для добавления текста. The following code illustrates the use of the OpenTextFile method to open a file for appending text:
См. также See also
Поддержка и обратная связь Support and feedback
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Have questions or feedback about Office VBA or this documentation? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь. Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
What Is a Text File?
How to open, edit, and convert text files
A text file is a file containing text, but there are several different ways to think about that, so it’s important to know the kind of text document you have before dealing with a program that can open or convert it.
Some text files use the .TXT file extension and don’t contain any images. Others might contain both images and text, but still be called a text file or even abbreviated as a «txt file,» which can be confusing.
Types of Text Files
In the general sense, a text file refers to any file that has only text and is void of images and other non-text characters. These sometimes use the TXT file extension but don’t necessarily need to. For example, a Word document that is an essay containing just text can be in the DOCX file format but still be called a text file.
Another kind of text file is the «plain text» file. This is a file that contains zero formatting (unlike RTF files), meaning nothing is bold, italic, underlined, colored, using a special font, etc. Several examples of plain text file formats include ones that end in XML, REG, BAT, PLS, M3U, M3U8, SRT, IES, AIR, STP, XSPF, DIZ, SFM, THEME, and TORRENT.
Of course, files with the .TXT file extension are text files, too, and are commonly used to store things that can be easily opened with any text editor or written to with a simple script. Examples might include storing step-by-step instructions for how to use something, a place to hold temporary information, or logs generated by a program (though those are usually stored in a LOG file).
«Plaintext,» or cleartext files, are different than «plain text» files (with a space). If file storage encryption or file transfer encryption isn’t used, the data can be said to exist in plaintext or be transferred over plaintext. This can be applied to anything that should be secured but isn’t, be it emails, messages, plain text files, passwords, etc., but it’s usually used in reference to cryptography.
How to Open a Text File
All text editors should be able to open any text file, especially if there isn’t any special formatting being used. For example, TXT files can be opened with the built-in Notepad program in Windows by right-clicking the file and choosing Edit. Similar for TextEdit on a Mac.
Another free program that can open any text file is Notepad++. Once installed, you can right-click the file and choose Edit with Notepad++.
Most web browsers and mobile devices can open text files as well. However, since most of them aren’t built to load text files using the various extensions you mind them using, you might need to first rename the file extension to .TXT if you want to use those applications to read the file.
Some other text editors and viewers include Microsoft Word, TextPad, Notepad2, Geany, and Microsoft WordPad.
Additional text editors for macOS include BBEdit and TextMate. Linux users can also try the Leafpad, gedit, and KWrite text openers/editors.
Open Any File as a Text Document
Something else to understand here is that any file can be opened as a text document even if it doesn’t contain readable text. Doing this is useful when you’re not sure what file format it’s really in, like if it’s missing a file extension or you think it’s been identified with an incorrect file extension.
For example, you can open an MP3 audio file as a text file by plugging it into a text editor like Notepad++. You can’t play the MP3 this way but you can see what it’s made up of in text form since the text editor is only able to render the data as text.
With MP3s in particular, the very first line should include «ID3» to indicate that it’s a metadata container that might store information like an artist, album, track number, etc.
Another example is the PDF file format; every file starts off with the «%PDF» text on the first line even though the rest of the document is completely unreadable.
How to Convert Text Files
The only real purpose for converting text files is to save them into another text-based format like CSV, PDF, XML, HTML, XLSX, etc. You can do this with most advanced text editors but not the simpler ones since they generally only support basic export formats like TXT, CSV, and RTF.
For example, the Notepad++ program mentioned above is capable of saving to a huge number of file formats, like HTML, TXT, NFO, PHP, PS, ASM, AU3, SH, BAT, SQL, TEX, VGS, CSS, CMD, REG, URL, HEX, VHD, PLIST, JAVA, XML, and KML.
Other programs that export to a text format can probably save to a few different kinds, typically TXT, RTF, CSV, and XML. So if you need a file from a specific program to be in a new text format, consider returning to the application that made the original text file, and export it to something else.
All that said, text is text so long as it’s plain text, so simply renaming the file, swapping one extension for another, might be all you need to do to «convert» the file.
See our list of Free Document Converter Software Programs for some additional file converters that work with various types of text files.
Is Your File Still Not Opening?
Are you seeing jumbled text when you open your file? Maybe most of it, or all of it, is completely unreadable. The most likely reason for this is that the file isn’t plain text.
Like we mentioned above, you can open any file with Notepad++, but like with the MP3 example, it doesn’t mean that you can actually use the file there. If you try your file in a text editor and it’s not rendering like you think it should, rethink how it should open; it’s probably not in a file format that can be explained in human-readable text.
If you have no idea how your file should open, consider trying some popular programs that work with a wide variety of formats. For example, while Notepad++ is great for seeing the text version of a file, try dragging your file into VLC media player to check if it’s a media file that contains video or sound data.
Open text file and program shortcut in a Windows batch file
I have two files in the same folder that I’d like to run. One is a .txt file, and the other is the program shortcut to an .exe . I’d like to make a batch file in the same location to open the text file and the shortcut then close the batch file (but the text file and program remain open).
I tried this with no luck:
Also didn’t work:
12 Answers 12
I was able to figure out the solution:
This would have worked too. The first quoted pair are interpreted as a window title name in the start command.
Don’t put quotes around the name of the file that you are trying to open; start «myfile.txt» opens a new command prompt with the title myfile.txt , while start myfile.txt opens myfile.txt in Notepad. There’s no easy solution in the case where you want to start a console application with a space in its file name, but for other applications, start «» «my file.txt» works.
The command-line syntax for opening a text file is:
File types supported by this command include (but are not limited to): .doc, .txt, .html, .log
If the contents is too long, you can add «|more» after «type filename.txt», and it will pause after each screen; to end the command before the end of the file, you can hold Ctrl + C .
to open the file.
Another example is
You can also do:
The C:\Users\kemp\Install\ is your PATH. The Text1.txt is the FILE.
«location of notepad file» > notepad Filename
C:\Users\Desktop\Anaconda> notepad myfile
In some cases, when opening a LNK file it is expecting the end of the application run.
In such cases it is better to use the following syntax (so you do not have to wait the end of the application):
To open a TXT file can be in the way already indicated (because notepad.exxe not interrupt the execution of the start command)
The command start [filename] opened the file in my default text editor.
This command also worked for opening a non-.txt file.
If you are trying to open an application such as Chrome or Microsoft Word use this:
And repeat this for all of the applications you want to open.