Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Learn Python in 7 Days

You're reading from   Learn Python in 7 Days Begin your journey with Python

Arrow left icon
Product type Paperback
Published in May 2017
Publisher Packt
ISBN-13 9781787288386
Length 280 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
 Das Das
Author Profile Icon Das
Das
Arrow right icon
View More author details
Toc

Table of Contents (18) Chapters Close

Title Page
Credits
About the Authors
About the Reviewer
www.PacktPub.com
Customer Feedback
Preface
1. Getting Started with Python FREE CHAPTER 2. Type Variables and Operators 3. Strings 4. Lists 5. Dictionary 6. Control Statements and Loops 7. Function and Scope of Variable 8. Modules and Packages 9. File Handling and Exceptions 10. Collections 11. Class and Objects

Reading text from a file 


In order to read and write into a file, we will use the open() built-in function to open the file. The open() function creates an file_object object. What is an object?  You will understand in  Chapter 11, Class and Objects.  The Syntax is given as:

file_object = open(file_name ,access_mode)

The first argument,file_name, specifies the filename that you want to open. The second argument, access_mode, determines in which mode the file has to be opened, that is, read, write, append, and so on. 

The read() method

Now we will read a file by a program. The access mode for reading is r.

Let's take the sample of a text file containing famous quotes:

Sample file

I have saved the preceding file with the name sample1.txt.

Let's write a readfile.py program to read the earlier file: 

file_input = open("sample1.txt",'r')
all_read = file_input.read()
print all_read
file_input.close() 

In the given code, first we created a file_input file object, then we called file_input.read() to read...

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime
Visually different images