Net-informations.com
SiteMap  | About    

How to read a file in python

File handling in Python requires no importing of modules. The File object provides basic functions and methods necessary to manipulate files by default. Python gives you easy ways to manipulate these files. In order to read data from a file, first of all, you need to open it in reading mode. Then, you can call anyone of the methods that Python provides for reading from a file.

There are actually a number of ways to read a text file in Python. The read functions contains different methods, read(),readline() and readlines()

  1. read([number]) : Return specified number of characters from the file. if omitted it will read the entire contents of the file.

  2. readline() : Return the next line of the file.

  3. readlines() : Read all the lines as a list of strings in the file

Read entire content of file at once

output

Reading only one line

output

Reading data using size

output

Reading all lines as an array

output

Read file line by line

If you want to read all the lines from a file in a more memory efficient, you can use the loop over method.

example

output

File Positions

Python tell() Method

The method tell() returns the current position of the file read/write pointer within the file.

example

output

Python seek() method

The seek() method sets the file's current position at the offset.

example

output

Splitting lines from a text file in Python

The following Python program reading a text file and splitting it into single words in python

example

output









net-informations.com (C) 2017    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.