Python tutorial- read data from file


read data from a file

To read data from the file, you can use read() method.
>>> f=open('Python_source\\test.txt','r')
>>> content=f.read(5)
>>> print content
Hello
>>>content=f.read()
>>>print content
World

In the code above, we read only 5 characters from the file. To read the rest of the file, just write f.read().
Note: When the first 5 characters were read, file marker was moved to the position of character sixth. To read data one line at a time, the method readline() is used.
>>> f=open('Python_source\\test.txt','r')
>>> content=f.readline()
>>> while content:
            print content
            content=f.readline()
           
While C, and C++ programs run fast, Python programs run slower.
 
But Python is easy to learn and save development time.
>>> 
 If you want to read all lines of data from the file, use readlines() method.


Comments




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.