Read data from text file (2024)

Read data from text file

collapse all in page

Syntax

A = fscanf(fileID,formatSpec)

A = fscanf(fileID,formatSpec,sizeA)

[A,count]= fscanf(___)

Description

example

A = fscanf(fileID,formatSpec) readsdata from an open text file into column vector A andinterprets values in the file according to the format specified by formatSpec.The fscanf function reapplies the format throughoutthe entire file and positions the file pointer at the end-of-filemarker. If fscanf cannot match formatSpec tothe data, it reads only the portion that matches and stops processing.

The text file is indicated by the file identifier, fileID.Use fopen to open the file, specify the characterencoding, and obtain the fileID value. When youfinish reading, close the file by calling fclose(fileID).

example

A = fscanf(fileID,formatSpec,sizeA) readsfile data into an array, A, with dimensions, sizeA,and positions the file pointer after the last value read. fscanf populates A incolumn order. sizeA must be a positive integeror have the form [m n], where m and n arepositive integers.

example

[A,count]= fscanf(___) additionally returns the numberof fields that fscanf reads into A.For numeric data, this is the number of values read. You can use thissyntax with any of the input arguments of the previous syntaxes.

Examples

collapse all

Read File Contents into Column Vector

Open Live Script

Create a sample text file that contains floating-point numbers.

x = 100*rand(8,1);fileID = fopen('nums1.txt','w');fprintf(fileID,'%4.4f\n',x);fclose(fileID);

View the contents of the file.

type nums1.txt
81.472490.579212.698791.337663.23599.754027.849854.6882

Open the file for reading, and obtain the file identifier, fileID.

fileID = fopen('nums1.txt','r');

Define the format of the data to read. Use '%f' to specify floating-point numbers.

formatSpec = '%f';

Read the file data, filling output array, A, in column order. fscanf reapplies the format, formatSpec, throughout the file.

A = fscanf(fileID,formatSpec)
A = 8×1 81.4724 90.5792 12.6987 91.3376 63.2359 9.7540 27.8498 54.6882

A is a column vector containing data from the file.

Close the file.

fclose(fileID);

Read File Contents into Array

Open Live Script

Create a sample text file that contains integers and floating-point numbers.

x = 1:1:5;y = [x;rand(1,5)];fileID = fopen('nums2.txt','w');fprintf(fileID,'%d %4.4f\n',y);fclose(fileID);

View the contents of the file.

type nums2.txt
1 0.81472 0.90583 0.12704 0.91345 0.6324

Open the file for reading, and obtain the file identifier, fileID.

fileID = fopen('nums2.txt','r');

Define the format of the data to read and the shape of the output array.

formatSpec = '%d %f';sizeA = [2 Inf];

Read the file data, filling output array, A, in column order. fscanf reuses the format, formatSpec, throughout the file.

A = fscanf(fileID,formatSpec,sizeA)
A = 2×5 1.0000 2.0000 3.0000 4.0000 5.0000 0.8147 0.9058 0.1270 0.9134 0.6324
fclose(fileID);

Transpose the array so that A matches the orientation of the data in the file.

A = A'
A = 5×2 1.0000 0.8147 2.0000 0.9058 3.0000 0.1270 4.0000 0.9134 5.0000 0.6324

Skip Specific Characters in File

Skip specific characters in a sample file,and return only numeric data.

Create a sample text file containing temperature values.

str = '78°C 72°C 64°C 66°C 49°C';fileID = fopen('temperature.dat','w');fprintf(fileID,'%s',str);fclose(fileID);

Read the numbers in the file, skipping the text, °C.Also return the number of values that fscanf reads.The extended ASCII code 176 represents the degree sign.

fileID = fopen('temperature.dat','r');degrees = char(176);[A,count] = fscanf(fileID, ['%d' degrees 'C'])fclose(fileID);
A = 78 72 64 66 49count = 5

A is a vector containing the numeric valuesin the file. count indicates that fscanf readfive values.

Input Arguments

collapse all

fileIDFile identifier
integer

File identifier of an open text file, specified as an integer.Before reading a file with fscanf, you must use fopen toopen the file and obtain the fileID.

Data Types: double

formatSpecFormat of data fields
character vector | string scalar

Format of the data fields in the file, specified as a charactervector or string scalar of one or more conversion specifiers. When fscanf readsa file, it attempts to match the data to the format specified by formatSpec.

Numeric Fields

This table lists available conversion specifiers for numericinputs. fscanf converts values to their decimal(base 10) representation.

Numeric Field TypeConversion SpecifierDetails

Integer, signed

%d

Base 10

%i

The values in the file determine the base:

  • The default is base 10.

  • If the initial digits are 0x or 0X,then the values are hexadecimal (base 16).

  • If the initial digit is 0, thenvalues are octal (base 8).

%ld or %li

64-bit values, base 10, 8, or 16

Integer, unsigned

%u

Base 10

%o

Base 8 (octal)

%x

Base 16 (hexadecimal)

%lu, %lo, %lx

64-bit values, base 10, 8, or 16

Floating-point number

%f

Floating-point fields can containany of the following (not case sensitive): Inf, -Inf, NaN,or -NaN.

%e

%g

Character Fields

This table lists available conversion specifiers for characterinputs.

Character Field TypeConversion SpecifierDescription

Character vector or string scalar

%s

Read all characters excluding white spaces.

%c

Read any single character, including white space.
Toread multiple characters at a time, specify field width.

Pattern-matching

%[...]

Read only characters in the brackets up to the firstnonmatching character or white space.

Example: %[mus] reads 'summer' as 'summ'.

If formatSpec contains a combination of numericand character specifiers, then fscanf convertseach character to its numeric equivalent. This conversion occurs evenwhen the format explicitly skips all numeric values (for example, formatSpec is '%*d%s').

Optional Operators

  • Fields and Characters to Ignore

    fscanf reads all numeric values and charactersin your file in sequence, unless you tell it to ignore a particularfield or a portion of a field. To skip fields, insert an asterisk (*) after the percent sign (%).For example, to skip integers, specify %*d.

  • Field Width

    To specify the maximum number of digits or text characters toread at a time, insert a number after the percent character. For example, %10c readsup to 10 characters at a time, including white space. %4f readsup to 4 digits at a time, including the decimal point.

  • Literal Text to Ignore

    fscanf ignores specified text appended tothe formatSpec conversion specifier.

    Example: Level%u reads 'Level1' as 1.

    Example: %uStep reads '2Step' as 2.

sizeADimensions of output array
Inf (default) | integer | two-element row vector

Dimensions of the output array, A, specifiedas Inf, an integer, or a two-element row vector.

Form of the sizeA InputDescription
InfRead to the end of the file.
For numeric data,the output, A, is a column vector.
Fortext data, A is a character vector.
nRead at most n numeric values orcharacter fields.
For numeric data, the output, A,is a column vector.
For text data, A,is a character vector.
[m,n]Read at most m*n numericvalues or character fields. n can be Inf,but m cannot. The output, A,is m-by-n, filled in columnorder.

Output Arguments

collapse all

A — File data
column vector | matrix | character vector | character array

File data, returned as a column vector, matrix, character vectoror character array. The class and size of A dependon the formatSpec input:

  • If formatSpec contains only numericspecifiers, then A is numeric. If you specify the sizeA argument,then A is a matrix of the specified size. Otherwise, A isa column vector. If the input contains fewer than sizeA values,then fscanf pads A with zeros.

    • If formatSpec contains only 64-bitsigned integer specifiers, then A is of class int64.

    • If formatSpec contains only 64-bitunsigned integer specifiers, then A is of class uint64.

    • Otherwise, A is of class double.

  • If formatSpec contains only characteror text specifiers (%c or %s),then A is a character array. If you specify sizeA andthe input contains fewer characters, then fscanf pads A with char(0).

  • If formatSpec contains a combinationof numeric and character specifiers, then A isnumeric, of class double, and fscanf convertseach text characters to its numeric equivalent. This occurs even when formatSpec explicitlyskips all numeric fields (for example, formatSpec is '%*d%s').

  • If MATLAB® cannot match the file data to formatSpec,then A can be numeric or a character array. Theclass of A depends on the values that fscanf readsbefore it stops processing.

count — Number of characters read
scalar

Number of characters read, returned as a scalar value.

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.

Algorithms

MATLAB reads characters using the encoding scheme associatedwith the file. You specify the encoding when you open the file usingthe fopen function.

Extended Capabilities

Version History

Introduced before R2006a

expand all

This function supports thread-based environments.

See Also

fopen | fprintf | textscan | sscanf | fgetl | fgets | fread

Topics

  • Import Text Data Files with Low-Level I/O

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.

Read data from 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

Read data from text file (2024)

FAQs

How do I read data from a TXT file? ›

There are three ways to read data from a text file:
  1. Using read()
  2. Using readline()
  3. Using readlines()
Jun 19, 2024

Which function is used to read data from text file? ›

Reading and writing text files normally uses the fprintf and fscanf functions, which are easily understood by anyone who knows printf and scanf.

What can read a text file? ›

Text file formats can be opened using text editor applications such as Notepad or TextEdit or specific programmes such as Microsoft Word. They can also be commonly converted to other document types - for example a PDF, using Adobe Acrobat.

How to read a txt file into Python? ›

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.

Can Excel read txt files? ›

csv) files. There are two ways to import data from a text file with Excel: you can open it in Excel, or you can import it as an external data range. To export data from Excel to a text file, use the Save As command and change the file type from the drop-down menu.

What programs can read txt files? ›

Microsoft Word. Microsoft Notepad. Apple TextEdit. Leafpad and gedit for Linux.

What is a function that reads a text file? ›

In order to read the content of filename.txt , we can use the fgets() function.

Which class can you use to read data from a text file? ›

Using scanner to read text file in java

If you want to read file line by line or based on some java regular expression, Scanner is the class to use.

Which method is used to read from a file? ›

The read() method returns the entire contents of the file as a single string (or just some characters if you provide a number as an input parameter. The readlines method returns the entire contents of the entire file as a list of strings, where each item in the list is one line of the file.

How do I view a .txt file? ›

Smartphone (Android or iOS)

In addition to the Microsoft 365 Mobile Apps included in Office packages, like Word, the Google Docs app is also available on Android devices. On iOS, the free app File Aid is a good choice, and on iPad, you can use the Pages app.

What are the disadvantages of text files? ›

One of the main disadvantages of using text files is that they are not well-suited for storing large amounts of data or for storing complex data structures. They also lack some of the features of more advanced file formats, such as the ability to store images or other types of multimedia data.

Can Word read txt files? ›

Open the text file in Word. In the Open dialog in Word, select 'Text Files (*. txt)' from the file type drop down. Save it as a Word document.

What is the process of retrieving data from a file called? ›

The process of retrieving data from a file is known as reading data from the file.

How to extract data from txt in Python? ›

Reading Line/Lines from a Text File
  1. readline() -> str: (most commonly-used) Read next line (up to and including newline) and return a string (including newline). ...
  2. readlines() -> [str]: Read all lines into a list of strings.
  3. read() -> str: Read the entire file into a string.

What feature do you use to import data from a text file? ›

Although you can't export to Excel directly from a text file or Word document, you can use the Text Import Wizard in Excel to import data from a text file into a worksheet.

How do I view a .TXT file? ›

Smartphone (Android or iOS)

In addition to the Microsoft 365 Mobile Apps included in Office packages, like Word, the Google Docs app is also available on Android devices. On iOS, the free app File Aid is a good choice, and on iPad, you can use the Pages app.

How do I read a string from a text file? ›

The Solution
  1. open("dna. txt", "r") opens the file in read mode ( r ). ...
  2. file. read() reads the entire contents of the file into a string.
  3. replace("\n", "") is a string method that replaces all newline characters in our string with empty strings.
Nov 15, 2023

How do I read a file type data? ›

Below are some of the ways by which we can read .data files in Python:
  1. Reading the .data Text File.
  2. Reading the . data Binary File.
  3. Reading . data Files Using Built-in Python Functions.
  4. Reading . data Files Using Pandas.
  5. Numerical Data Extraction Using NumPy.
Feb 1, 2024

Can phones read TXT files? ›

The text viewer will help you in reading text files on the text viewer app. The text viewer app for android will allow users to view read any . txt file in the text view app. You can avail text viewer search feature to find the desired file you're looking for.

Top Articles
Latest Posts
Article information

Author: Foster Heidenreich CPA

Last Updated:

Views: 6442

Rating: 4.6 / 5 (56 voted)

Reviews: 87% of readers found this page helpful

Author information

Name: Foster Heidenreich CPA

Birthday: 1995-01-14

Address: 55021 Usha Garden, North Larisa, DE 19209

Phone: +6812240846623

Job: Corporate Healthcare Strategist

Hobby: Singing, Listening to music, Rafting, LARPing, Gardening, Quilting, Rappelling

Introduction: My name is Foster Heidenreich CPA, I am a delightful, quaint, glorious, quaint, faithful, enchanting, fine person who loves writing and wants to share my knowledge and understanding with you.