Sunteți pe pagina 1din 1

Microsoft: DEV274x

Introduction to Python: Fundamentals Help zahideme 

Course Discussion Wiki Progress

Course  Module 4 Files  Files import, open & read  .read() method

 Previous        Next 

Audit Access Expires Apr. 14, 2019


You lose all access to this course, including your progress, on Apr. 14, 2019.
Upgrade by Mar. 31, 2019 to get:
Unlimited access as long as the course exists
Graded problems and exams
Certi cate of completion
Upgrade now

.read() method
 Bookmark this page

.read() method
Start of transcript. Skip to the end.

We can read an open text le using the Read


Method.
In this example, I'm gonna read poem text is a
text
le that I've imported into my Jupyter Notebook
and
then I've opened it in read.
And then, i want to assign it to this variable.
And it's gonna import that text as a string
including all the whitespace new line characters
("\n").
 0:04 / 1:18  Speed 1.0x  HD     So I'm gonna go ahead and do that right now.

Video Transcripts
Download video le Download SubRip (.srt) le
Download Text (.txt) le

Concept

Read a le using .read()

reading text
poem_contents = poem_file.read()

.read() loads the content of the le into memory as a string, including formatting such as new line (\n)
Examples

examples expect that the cells that import and open of poem1.txt has been run without a read()
Run the cells that import and open poem1.txt

# [ ] review and run example


poem_contents = poem_file.read()

# [ ] review and run example


# shows the file as a string with formatting characters such as "\n", output should be non-blank
poem_contents

# [ ] review and run example


# since .read() loaded the file as a string it can be printed
print(poem_contents)

Task 2
read a le

Read the le cities.text that was imported in task 1

1. import cities.txt and open

1. ensure the code was created and run in task 1 to import cities.txt

2. create and run code to re-open cities.txt as cities_ le

2. read() cities_ le into a variable called cities

3. Test the read() by displaying the string contained in cities

4. Test the read() by printing the cities string

# [ ] after import and open of cities.txt in task 1


# [ ] read cities_file as cities
# [ ] display the string: cities

# [ ] print the string: cities

 Previous Next 

Learn About Veri ed Certi cates


© All Rights Reserved

edX Legal Connect


     
About Terms of Service & Blog
edX for Business Honor Code Contact Us
Privacy Policy Help Center
Accessibility Policy

© 2012–2019 edX Inc.


EdX, Open edX, and MicroMasters are
registered trademarks of edX Inc. | 粤ICP备
17044299号-2

S-ar putea să vă placă și