Programming with Python

⌘K
  1. Home
  2. Docs
  3. Programming with Python
  4. Files, Modules and Packag...
  5. Files
  6. File Operations
  7. Reading files

Reading files

File Read

To read data from a file, open the file in read mode. Methods to read data from a text file

Read

The read( ) method is used to read a string from an already opened file. The string can include alphabets, numbers, characters or other symbols

Syntax

read( )
Fileobj.read(count)
  • Count is an optional parameter, which if passed to the read( ) method specifies the number of bytes to read from the opened file.
  • The read( ) method starts reading from the beginning of the file and if count is missing or has a negative value, then it reads the entire the content of the file(i.e., till the end of file)

Example

Python is easy 
problem solving 
python programming
GE8151
GE8161
file1 = open("myfile1.txt", "r")
print(file1.read(7))
file1.close()

Output

Python

readline

The readline( ) method is used to read a single line from the file. The method returns an empty string when the end of the file has been reached.

Syntax

readline( )
Fileobj.readline( )

Example

file1 = open("myfile1.txt", "r")
print(file1.readline())
print(file1.readline())
file1.close()

Output

Python is easy
problem solving

readlines

The readlines( ) method is used to read all the lines in the file.

Syntax

readlines( )

Example

file1 = open("myfile1.txt", "r")
print(file1.readlines())
file1.close()

Output

['Python is easy \n', 'problem solving \n', 'python programming\n', 'GE8151\n', 'GE8161']

Views: 0

How can we help?

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments