Reading a file Flashcards

You may prefer our related Brainscape-certified flashcards:
1
Q

Opening a file

A
with open(example1, "r") as file1:
    FileContent = file1.read()
    print(FileContent)
This is line 1 
This is line 2
This is line 3
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Read first 4 characters

A

We don’t have to read the entire file, for example, we can read the first 4 characters by entering three as a parameter to the method .read():

# Read first four characters
​
with open(example1, "r") as file1:
    print(file1.read(4))
This
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Readline()

A

We can also pass an argument to readline() to specify the number of charecters we want to read. However, unlike read(), readline() can only read one line at most.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Read () vs. readline()

A

with open(example1, “r”) as file1:
print(file1.readline(20)) # does not read past the end of line
print(file1.read(20)) # Returns the next 20 chars

This is line 1

This is line 2
This

How well did you know this?
1
Not at all
2
3
4
5
Perfectly