Write data to text file (2024)

Write data to text file

collapse all in page

Syntax

fprintf(fileID,formatSpec,A1,...,An)

fprintf(formatSpec,A1,...,An)

nbytes = fprintf(___)

Description

example

fprintf(fileID,formatSpec,A1,...,An) appliesthe formatSpec to all elements of arrays A1,...An incolumn order, and writes the data to a text file. fprintf usesthe encoding scheme specified in the call to fopen.

example

fprintf(formatSpec,A1,...,An) formats data and displays the results on the screen.

example

nbytes = fprintf(___) returnsthe number of bytes that fprintf writes, usingany of the input arguments in the preceding syntaxes.

Examples

collapse all

Print Literal Text and Array Values

Open Live Script

Print multiple numeric values and literal text to the screen.

A1 = [9.9, 9900];A2 = [8.8, 7.7 ; ... 8800, 7700];formatSpec = 'X is %4.2f meters or %8.3f mm\n';fprintf(formatSpec,A1,A2)
X is 9.90 meters or 9900.000 mmX is 8.80 meters or 8800.000 mmX is 7.70 meters or 7700.000 mm

%4.2f in the formatSpec input specifies that the first value in each line of output is a floating-point number with a field width of four digits, including two digits after the decimal point. %8.3f in the formatSpec input specifies that the second value in each line of output is a floating-point number with a field width of eight digits, including three digits after the decimal point. \n is a control character that starts a new line.

Print Double-Precision Values as Integers

Open Live Script

Explicitly convert double-precision values with fractions to integer values.

135

%d in the formatSpec input prints each value in the vector, round(a), as a signed integer. \n is a control character that starts a new line.

Write Tabular Data to Text File

Write a short table of the exponential functionto a text file called exp.txt.

x = 0:.1:1;A = [x; exp(x)];fileID = fopen('exp.txt','w');fprintf(fileID,'%6s %12s\n','x','exp(x)');fprintf(fileID,'%6.2f %12.8f\n',A);fclose(fileID);

The first call to fprintf prints headertext x and exp(x), and the secondcall prints the values from variable A.

If you plan to read the file with Microsoft® Notepad,use '\r\n' instead of '\n' tomove to a new line. For example, replace the calls to fprintf withthe following:

fprintf(fileID,'%6s %12s\r\n','x','exp(x)');fprintf(fileID,'%6.2f %12.8f\r\n',A);

MATLAB® import functions, all UNIX® applications, and Microsoft Word andWordPad recognize '\n' as a newline indicator.

View the contents of the file with the type command.

type exp.txt
 x exp(x) 0.00 1.00000000 0.10 1.10517092 0.20 1.22140276 0.30 1.34985881 0.40 1.49182470 0.50 1.64872127 0.60 1.82211880 0.70 2.01375271 0.80 2.22554093 0.90 2.45960311 1.00 2.71828183

Get Number of Bytes Written to File

Open Live Script

Write data to a file and return the number of bytes written.

Write an array of data, A, to a file and get the number of bytes that fprintf writes.

A = magic(4);fileID = fopen('myfile.txt','w');nbytes = fprintf(fileID,'%5d %5d %5d %5d\n',A)
nbytes = 96

The fprintf function wrote 96 bytes to the file.

Close the file.

fclose(fileID);

View the contents of the file with the type command.

type('myfile.txt')
 16 5 9 4 2 11 7 14 3 10 6 15 13 8 12 1

Display Hyperlinks in Command Window

Display a hyperlink (The MathWorks Web Site) onthe screen.

url = 'https://www.mathworks.com';sitename = 'The MathWorks Web Site';fprintf('<a href = "%s">%s</a>\n',url,sitename)

%s in the formatSpec inputindicates that the values of the variables url and sitename,should be printed as text.

Input Arguments

collapse all

fileIDFile identifier
1 (default) | 2 | scalar

Fileidentifier, specified as one of the following:

  • A file identifier obtained from fopen.

  • 1 for standard output (the screen).

  • 2 for standard error.

Data Types: double

A1,...,AnNumeric or character arrays
scalar | vector | matrix | multidimensional array

Numeric or character arrays, specified as a scalar, vector,matrix, or multidimensional array.

Data Types: single | double | int8 | int16 | int32 | int64 | uint8 | uint16 | uint32 | uint64 | logical | char

Output Arguments

collapse all

nbytes — Number of bytes
scalar

Number of bytes that fprintf writes, returnedas a scalar. When writing to a file, nbytes isdetermined by the character encoding. When printing data to the screen, nbytes isthe number of characters displayed on the screen.

Tips

  • Format specifiers for the reading functions sscanf and fscanf differfrom the formats for the writing functions sprintf and fprintf.The reading functions do not support a precision field. The widthfield specifies a minimum for writing, but a maximum for reading.

  • If you specify an invalid formatting operator or special character, then fprintf prints all text up to the invalid operator or character and discards the rest.

    Example: If formatSpec is 'value = %z', then fprintf prints 'value =' because %z is not a formatting operator.

    Example: If formatSpec is 'character \x99999 = %s', then fprintf prints 'character' because \x99999 is not a valid special character.

References

[1] Kernighan, B. W., and D. M. Ritchie, TheC Programming Language, Second Edition, Prentice-Hall,Inc., 1988.

[2] ANSI specification X3.159-1989: “ProgrammingLanguage C,” ANSI, 1430 Broadway, New York, NY 10018.

Extended Capabilities

Version History

Introduced before R2006a

See Also

disp | fclose | ferror | fopen | fread | fscanf | fwrite | fseek | ftell | sprintf

Topics

  • Export Cell Array to Text File
  • Append to or Overwrite Existing Text Files
  • Formatting Text

MATLAB Command

You clicked a link that corresponds to this MATLAB command:

 

Run the command by entering it in the MATLAB Command Window. Web browsers do not support MATLAB commands.

Write data to text file (1)

Select a Web Site

Choose a web site to get translated content where available and see local events and offers. Based on your location, we recommend that you select: .

You can also select a web site from the following list:

Americas

  • América Latina (Español)
  • Canada (English)
  • United States (English)

Europe

  • Belgium (English)
  • Denmark (English)
  • Deutschland (Deutsch)
  • España (Español)
  • Finland (English)
  • France (Français)
  • Ireland (English)
  • Italia (Italiano)
  • Luxembourg (English)
  • Netherlands (English)
  • Norway (English)
  • Österreich (Deutsch)
  • Portugal (English)
  • Sweden (English)
  • Switzerland
    • Deutsch
    • English
    • Français
  • United Kingdom (English)

Asia Pacific

Contact your local office

Write data to text file (2024)

FAQs

How do you write data to a text file in Python? ›

The write() function is used for writing the string in the text file, and the writelines() function is used for writing the list of the string in the file at once. The writelines() function can also accept the iterable object. The user can also pass the tuple of strings, the set of strings, etc.

How do I write a string to a text file? ›

Writing to a File
  1. Problem. You want to write text or data to a file.
  2. Solution. Here is the most convenient way to write one big string to a file: open('thefile.txt', 'w').write(all_the_text) # text to a text file open('abinfile', 'wb').write(all_the_data) # data to a binary file. ...
  3. Discussion. ...
  4. See Also.

How do I create a .txt file? ›

The easiest way to create a text file in Windows is to open up the Notepad program on your computer. The Notepad is a text editor included with Microsoft Windows. A text file is considered a plaintext file and Notepad is only capable of creating and editing plaintext files. Notepad saves any text file with a .

What is writing data to a file? ›

Data is written to a file using the PRINTF statement. The statement may include the FORMAT keyword to control the specific structure of the written file. Format rules are needed when writing an array to a file. Example 1. Writing data to a file using simple format rules in the PRINTF procedure.

How do you send data to a text file in Python? ›

To write to a file in Python using a for statement, you can follow these steps: Open the file using the open() function with the appropriate mode ('w' for writing). Use the for statement to loop over the data you want to write to the file. Use the file object's write() method to write the data to the file.

How do you copy data into a text file in Python? ›

Steps to Copy a File using Python
  1. Step 1: Capture the source path. To begin, capture the path where your file is currently stored. ...
  2. Step 2: Capture the target path. Next, capture the target path where you'd like to copy the file. ...
  3. Step 3: Copy the file in Python using shutil. copyfile.

How do I create a TXT file in Python? ›

To create a file in Python, you can use the open() function with the 'a' mode such as file = open('myfile. txt', 'a') . This function opens a file for writing, creating the file if it does not exist. In this example, we're using the open() function to create a file named 'myfile.

What program makes TXT files? ›

They can be created and modified in a wide range of ways, most commonly with a text editor or a word processor. To create or edit . TXT files on Windows, open the built-in Notepad application.

What is txt file format? ›

A file with . TXT extension represents a text document that contains plain text in the form of lines.

What function can you use to write data to a file? ›

The write() method writes a specified text to the file.

What is a data text file? ›

The data values in text files are stored as a series of characters. The computer memory stores each character as one or two bytes and data (plain text) is generally arranged in rows, with each row containing several values.

What class do you use to write data to a file? ›

Java FileWriter class is used to write character-oriented data to a file. It is a character-oriented class that is used for file handling in java. This class inherits from OutputStreamWriter class which in turn inherits from the Writer class.

How do you load data into a text file in Python? ›

Importing Files (Reading Text Files)

In Python, you can use the open() function to read the . txt files. Notice that the open() function takes two input parameters: file path (or file name if the file is in the current working directory) and the file access mode.

How to store data in a text file in Python? ›

Saving a Text File in Python
  1. write(): Inserts the string str1 in a single line in the text file. File_object.write(str1)
  2. writelines(): For a list of string elements, each string is inserted in the text file. Used to insert multiple strings at a single time. File_object.writelines(L) for L = [str1, str2, str3]
Dec 29, 2020

How do you write a list of data into a text file in Python? ›

Method 2: Using writelines()
  1. Open a . txt file function in w mode (here w signifies write). The open() function shows the file path.
  2. Create a list of items.
  3. The writelines() function takes the list of items as its parameter and writes them in the text file.
  4. Close the file using the close() function.
May 3, 2023

How to convert data to text in Python? ›

The str() function takes in any python data type and converts it into a string. But use of the str() is not the only way to do so. This type of conversion can also be done using the “%s” keyword, the .format function or using f-string function.

References

Top Articles
Latest Posts
Article information

Author: Terence Hammes MD

Last Updated:

Views: 6688

Rating: 4.9 / 5 (49 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Terence Hammes MD

Birthday: 1992-04-11

Address: Suite 408 9446 Mercy Mews, West Roxie, CT 04904

Phone: +50312511349175

Job: Product Consulting Liaison

Hobby: Jogging, Motor sports, Nordic skating, Jigsaw puzzles, Bird watching, Nordic skating, Sculpting

Introduction: My name is Terence Hammes MD, I am a inexpensive, energetic, jolly, faithful, cheerful, proud, rich person who loves writing and wants to share my knowledge and understanding with you.